Petter Pettersson
Petter Pettersson

Reputation: 377

Java for loop to get X

I need help with a for loop I have for an assignment. There is a math problem called N!, I bet some of you have heard of it. It goes like 1*2*3*4*5*n=x I made a table like this:
1 = 1
1 * 2 = 2
1 * 2 * 3 = 6
1 * 2 * 3 * 4 = 24
1 * 2 * 3 * 4 * 5 = 120
1 * 2 * 3 * 4 * 5 * 6 = 720
But I just can't seem to solve the problem. How do I get what x is from 1*2*3*4....*n=x? Here's my code so far:

Scanner input = new Scanner(System.in);
    System.out.println("\n~~Assignment 8.5~~");
    boolean go = true;

    do {
        int n;
        int total;
        System.out.println("Loop until:");
        n = input.nextInt();
        for (int i = 1;i <= n;i++)
        {

            System.out.print(i);
            if (i == n) { System.out.print(" = " + "idk" + "\n"); break;}  else { System.out.print(" * ");}
        }
    } while ( go == true);

Upvotes: 0

Views: 152

Answers (4)

Daveman
Daveman

Reputation: 1095

int rec_n( int n){
    int result = 1;
    for(int i = 1; i <= n; i++ ){
        result *= i;
    }
    return result;
}

Upvotes: 0

mangr3n
mangr3n

Reputation: 309

Here's the hint,

fact(x) = x * fact(x-1) iff x > 0
fact(x) = 1             iff x == 0
fact(x) = ERROR         iff x < 0

Create and implement the function public int fact(int x) and call it from inside a main function after picking up input from the command line or from reading user input. (and validating the input is a number)

Upvotes: 0

Ahmet Karakaya
Ahmet Karakaya

Reputation: 10139

You can use following Class;

public class RecursiveTest {

public RecursiveTest(int x){
    int i=1;
    int temptotal=1;
    while(true){
        System.out.print(i+"*");
        if(temptotal==x || temptotal>x) break;          

        temptotal=temptotal*(++i);

    }

}

public static void main(String[] args) {
new     RecursiveTest(100);
}

}

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

Just add total calculation s inside the for loop:

total *= i;

and after the for loop print it. Remember to initialize total with value 1

Upvotes: 1

Related Questions