Java while loop calculate factorial

Question

We would like to calculate the factorial of a positive integer n.

The factorial is written as n! and pronounced "n factorial".

It is equal to the product of the positive integers from 1 to n.

Write an application that calculates the factorials of 1 through 20.


public class Main{
    public static void main(String[] args){
        for(int i=0; i<20; i++){
            System.out.printf("%d\n", getFactorial(i));
        }/*from w w  w  .j a v a  2s. c  o  m*/
    }
    // compute and return factorial
    // x! = x-1 * x-1 * x-1 * x-1 ...
    private static long getFactorial(int x){
       //your code
    }
}



public class Main{
    public static void main(String[] args){
        for(int i=0; i<20; i++){
            System.out.printf("%d\n", getFactorial(i));
        }
    }
    // compute and return factorial
    // x! = x-1 * x-1 * x-1 * x-1 ...
    private static long getFactorial(int x){
        long factorial = x;

        if(x > 1)
            x--;

        while(x > 0){
            factorial *= x;
            x--;
        }
        return factorial;
    }
}



PreviousNext

Related