this code is working fine for numbers 1 to 12 but after that its showing the wrong result can somebody explain ?
package logicProgramming; import java.util.Scanner; public class Factorial { public static void main(String[] args) { // TODO Auto-generated method stub Scanner KB=new Scanner(System.in); int t=KB.nextInt(); while (t-->0) { int b=KB.nextInt(); if(b>0 && b<21) { int f=b; for(int i=1;i<b;i++){ f=f*i; } System.out.println(f); } } } }
Advertisement
Answer
you need to use something longer than type int, 12 factorial is 479,001,600, the maximum integer value in Java is 2,147,483,647. 13 factorial gives 6,227,020,800, this is bigger than the type int can hold