for loop multiplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()

{

int x;
int y=1;

for(x=1 ; x<=12 ; x++ , y=y*x )
{

 



cout<<y<<'\n';



}
}


this code give x! ( x factorial).
whenever ,in x<=12 , we change the 12 to any number n where n>=1 and n<=12
the code works and give the (x factorial)
for example 12!=479001600

the problem begins with the number 13.
when we put 13 like this x<=13 or for(x=1 ; x<=13 ; x++ , y=y*x )

the compiler gives a wrong result : it gives 1932053504 which is wrong because the true result is 6227020800

so the question is WHY the compiler gives this wrong result????? with explanation , details , specifications and examples
The reason is that you are using type int. Ints are represented by 32 bits, one of which is a sign bit. Therefore there are 31 bits that contain the number. 2^31 is 2147483648 so any number which is larger than that cannot be represented by this data-type.

An unsigned int increases this limit to 4294967296

An unsigned long long gives you 64 bits. This will hold any number up to 1.844674407 X 1019.

Even then, this only increases the limit to 20!. If you need to go any higher, you need some big-number library.
Topic archived. No new replies allowed.