Factorial loop results are incorrect after the 5th iteration

前端 未结 4 2049
离开以前
离开以前 2021-01-19 07:38

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

4条回答
  •  太阳男子
    2021-01-19 07:53

    That is an Integer Overflow issue. Use long or unsigned long instead of int. (And as @Dunes suggested, your best bet is really BigInteger when working with very large numbers, because it will never overflow, theoretically)

    The basic idea is that signed int stores numbers between -2,147,483,648 to 2,147,483,647, which are stored as binary bits (all information in a computer are stored as 1's and 0's)

    Positive numbers are stored with 0 in the most significant bit, and negative numbers are stored with 1 in the most significant bit. If your positive number gets too big in binary representation, digits will carry over to the signed bit and turn your positive number into the binary representation of a negative one.

    Then when the factorial gets bigger than even what an unsigned int can store, it will "wrap around" and lose the carry-over from its most significant (signed) bit - that's why you are seeing the pattern of sometimes alternating positive and negative values in your output.

提交回复
热议问题