简体   繁体   中英

Factorial function yields incorrect values for the high parameters

This small program tests the two approaches of computing the factorial - by iteration and by recursion.

Factorial.cs:

using System;

namespace Functions
{
    public class Factorial
    {
        public static ulong CalcRecursively(int number)
        {
            if (number > 1)
                return (ulong)number * CalcRecursively(number - 1);
            if (number <= 1)
                return 1;

            return 0;
        }

        public static ulong Calc(int number)
        {
            ulong rValue=1;

            for (int i = 0; i < number; i++)
            {
                rValue = rValue * (ulong)(number - i);                
            }

            return rValue;

        }


    }
}

MainProgram.cs:

using System;

using Functions;
class FunctionClient
{


    public static void Main()
    {

        Console.WriteLine("{0}\n", Functions.Factorial.CalcRecursively(TESTED_VALUE));
        Console.WriteLine("{0}\n", Functions.Factorial.Calc(TESTED_VALUE));

        Console.ReadKey();

    }

    const int TESTED_VALUE = 60;

}

Console:

9727775195120271360
9727775195120271360

It's ok with low figures, but otherwise(f.ex. with 60) it outputs the incorrect values, according to the most reliable source on the internet . Could you point out my mistake? It's unbeliveable for me that the two totally different methods works wrong in exactly the same manner.

You are running into the limits of C#'s ulong data type. It is a 64-bit data structure which limits it to a maximum value of 18,446,744,073,709,551,615 according to MSDN .

If you do want to explore larger numbers, .NET 4 introduced the BigInteger structure you may be interested in.

using System.Numerics;

public static BigInteger Calc(int number)
{
    BigInteger rValue = 1;
    for (int i = 0; i < number; i++)
    {
        rValue = rValue * (ulong)(number - i);
    }
    return rValue;
}

And add a reference to System.Numerics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM