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 gettin
You're surpassing the capacity of the int
type (2,147,483,647), so your result is wrapping back around to the minimum int
value. Try using long
instead.
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:
long x = 1L;
for(int n = 1; n < 10; n++)
{
x *= n;
System.out.println(x);
}
1 2 6 24 120 720 5040 40320 362880
which shows successive factorials until 10!
is reached.
Also, as others have mentioned, if you need values bigger than what long
can support you should use BigInteger, which supports arbitrary precision.