Factorial Java Program

允我心安 提交于 2019-12-01 00:24:38

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);
}

Coding by Recursive function:

import java.util.Scanner;

public class Main {

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


     public static long factorialRecursive(int n) {
         if (n == 0 || n == 1 )
             return 1;

         return n * factorialRecursive(n - 1);
     }
}

source: learn.uncox.com

If the number is large, "stackoverflow" happens.

Fabinout

Why bother computing it?

public int factorial ( int n ) {
switch(n){
case 0: return 1;
case 1: return 1;
case 2: return 2;
case 3: return 6;
case 4: return 24;
case 5: return 120;
case 6: return 720;
case 7: return 5040;
case 8: return 40320;
case 9: return 362880;
case 10: return 3628800;
case 11: return 39916800;
case 12: return 479001600;
default : throw new IllegalArgumentException();
}

Source : @Emory

Merit Campus

This is My Program

class FactorialUsingFor
{
    public static void main(String arg[])
    {
        int factorial = 1;
        int number = 6;

        for(int i = 1; i <= number; i++)
        {
            factorial *= i;
        }

        System.out.println("Factorial of number " + number + " is " + factorial);

    }
}
int sum = 1;

for (int i = 2;i <= num;i++) {
    sum = sum * i;
}

Try this program:=

import java.util.*;
public class Factorials {
 public static void main(String[] args){
  Scanner sc=new Scanner(System.in);
  int i,num,a,b;
  int c=1;
  System.out.println("Enter the no.= ");
  num=sc.nextInt();
  for(i=1;i<=num;i++){
   c=i*c;
  }
  System.out.println("Factorial is "+c);
 }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!