Factorial loop results are incorrect after the 5th iteration

前端 未结 4 2081
离开以前
离开以前 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 08:02

    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.

提交回复
热议问题