1

I'm pretty new to programming. Doing a factorial problem, I'm getting back the incorrect values. I understand it's because they're too large, but I don't know how to fix it.

using System;

namespace Factorial
{
    class Program
    {
        public static long factoring(int n)
        {
            if (n == 0)
            {
                return 1;
            }
            return n * factoring(n - 1);
        }

        static void Main(string[] args)
        {
            int lines, value;
            lines = int.Parse(Console.ReadLine());

            for (int i = 0; i < lines; i++)
            {
                value = int.Parse(Console.ReadLine());
                Console.WriteLine(factoring(value));
            }
        }

    }
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • You could use BigInteger: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx – kren470 Jun 28 '14 at 18:29

1 Answers1

0

You should use checked keyword to explicitly enable overflow checking for integral-type arithmetic in order to avoid overflow, as detailed in http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx . In you case, like:

return checked(n * factoring(n - 1));

On overflow Function will throw exception instead of returning the wrong number. In case you need to operate with bigger Integer numbers, use Int64 or Decimal Type. In general, Integer factorial of big numbers (>20) is problematic, though approximate solutions exist. Rgds,

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42