Factorial values grow fast. Very, very fast:
n n!
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 6227020800
14 87178291200
15 1307674368000
16 20922789888000
17 355687428096000
18 6402373705728000
19 121645100408832000
20 2432902008176640000
25 1.5511210043E25
42 1.4050061178E51
50 3.0414093202E64
70 1.1978571670E100
100 9.3326215444E157
450 1.7333687331E1,000
1000 4.0238726008E2,567
3249 6.4123376883E10,000
(Source:
Wiki[
^]
And if you look at long - 4 bytes as you say - that's not a 64 bit number. 4 bytes is 4 * 8 == 32 bits, so the largest number it can store is 2,147,483,647...so your method "runs out of steam" at 12! and wraps back to a "random" number.
[edit]Wiki Table truncated and cleaned - OriginalGriff[/edit]
"thank you but why when I input bigger numbers than 12 I get wrong results??"
This all has to do with how computers store numbers. Lets just work with a smaller number of bits (or I have to lean on the "0" key for far too long( and assume that an int contaiuns just four bits.
Obviously, the largest number it can store is when each bit is '1' right? 1111b (or 0xF or 15 in decimal).
Wrong. If we did that, we would have nowhere to store negative numbers, because the "positiveness" or "negativeness" of a number needs a bit to store it.
Conventionally, computers use the highest, or left most bit to indicate negative numbers: any value with the "top bit" set is negative, and with it clear (or '0') the value is positive.
So the largest value we can store is 0111b (or 7 in hex and decimal) - the values range
0111b 7
0110b 6
0101b 5
0100b 4
0011b 3
0010b 2
0001b 1
0000b 0
1111b -1
1110b -2
1101b -3
1100b -4
1011b -5
1010b -6
1001b -7
1000b -8 or "negative zero" depending on the system.
So, when you add 2+3, your get 5:
0010b 2
+0011b 3
=0101b 5
But what happens when you add 5 + 6?
0101b 5
+0110b 6
=1011b -5
Arrggh! Noooooooo! But that is what happens - the "extra" bit from the addition of 0101b and 0110b moves into the "top bit" so the number becomes negative. If you continue to add to this then you will "overflow" the "top bit" as well, and at that point the result start to become very unpredictable and will vary depending on the system you run on, the compiler you use, the compilation switches you set and a host of other (mostly rather dull) effects.
And don't forget, multiplication is (at it's most basic) just a lot of adding up! :laugh:
When you scale this up to 32 bits, you get the same problems the moment you try to exceed 2,147,483,647 in an integer: because it's value is
0111111111111111111111111111111111111111111111111111111111111111 in binary. Add one, and it goes negative and your problems begin...:laugh: