Factorial in C family languages

后端 未结 4 1100
我寻月下人不归
我寻月下人不归 2021-01-29 06:42

I\'ve been trying to make a factorial function in C++, and I just found that inputs which are greater than 10 are not calculated correctly. I tried C# but I faced the same probl

4条回答
  •  臣服心动
    2021-01-29 06:48

    This is because factorials are big numbers and the don't fit in an int variable. It overflows. If You use unsigned long long instead of int, You can compute greater factorials.

    If the result doesn't need to be precise, You can use double as well. In the other case, You can implement the multiplication on arrays and You can compute as big factorials as You want.

    In C/C++, I recommend the GMP library

    And because you asked for C family languages: Java has a BigInteger type which is also useful.

提交回复
热议问题