Search code examples
javafor-loopfactorial

Factorial Java Program


I want to do a factorial program in java using a for loop. For example I want to take the user input, lets say 10, and then multiply 10*9*8*7*6*5*4*3*2*1. I need help constructing the for loop. The code below is all I have so far as I'm not sure where to go after.

import java.util.Scanner;
import java.lang.Math;
public class factorial {

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        num = input.nextInt();
    }
}

Solution

  • Try

    public static void main(String[] args) {
        int num;
        int fact=1;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        num = input.nextInt();
        for (int i=2;i<=num; i++){
            fact=fact*i;
        }
    
        System.out.println("Factorial: "+fact);
    }
    

    As @Marko Topolnik mentioned in comments this code will work for inputs up to 12. For larger inputs will output infinity due to overflow.

    For numbers larger than 12 you should use higher data type like BigInteger

    You can try:

    public static void main(String[] args) {
        BigInteger num;
        BigInteger fact = BigInteger.valueOf(1);
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        num = input.nextBigInteger();
        for (int i = 2; i <= num; i++){
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        System.out.println(fact);
    }