I am currently taking pre-calculus and thought that I would make a quick program that would give me the results of factorial 10. While testing it I noticed that I was getting incorrect results after the 5th iteration. However, the first 4 iterations are correct.
public class Factorial
{
public static void main(String[] args)
{
int x = 1;
int factorial;
for(int n = 10; n!=1; n--)
{
factorial = n*(n-1);
x = x * factorial;
System.out.printf("%d ", x);
}
}//end of class main
}//end of class factorial

You’re surpassing the capacity of the
inttype (2,147,483,647), so your result is wrapping back around to the minimumintvalue. Try usinglonginstead.Having said the that, the method you are currently employing will not result in the correct answer: actually, you are currently computing
10! ^ 2.Why complicate things? You could easily do something like this:
which shows successive factorials until
10!is reached.Also, as others have mentioned, if you need values bigger than what
longcan support you should useBigInteger, which supports arbitrary precision.