Java program to find factorial of a number


Factorial in Java

Factorial of a number N is represented by N! and it can be defined as follows:
0! = 1
N! = N * (N-1) * (N-2)* …. * 3*2*1
The factorial of a number N! is defined as the product of all the natural numbers from 1 to that particular number.
For example:
5! = 5 * 4 * 3 * 2 * 1 = 120
This is the Java code for factorial of a number:
import java.util.Scanner;
public class Factorial {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int N, result = 1;
        do {
            System.out.print("Please enter a value for N: ");                                                    
            N = input.nextInt();
        } while (N < 0);
        for (int i = 1; i <= N; i++) {
            result = result * i;
        }
        System.out.println(N + "! = " + result);
    }
}
Sample output:
Please enter a value for N: 10     
10! = 3628800
Here is the code using a method to calculate the factorial:
import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int N;
        do {
            System.out.print("Please enter a value for N: ");                                                     
            N = input.nextInt();
        } while (N < 0);
        System.out.println(N + "! = " + factorial(N));
    }

    //factorial of a number
    public static int factorial(int n){
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result = result * i;
        }
        return result;
    }

}
Factorial of greater numbers is too large for the int data type. If we input the value 22 we will obtain this output:
Please enter a value for N: 22     
22! = -522715136
The solution is to use double type to store the result:
//factorial of a number
    public static double factorial(int n){
        double result = 1;
        for (int i = 1; i <= n; i++) {                                                                            
            result = result * i;
        }
        return result;
    }

No comments :

Post a Comment