0

I have tried to make a simple factorial calculator in C#.

It works fine if the value entered is small enough( for instance, if I enter 5 it will print the correct output, 120);

However, if I enter 40, it will return me 0.

using System;

namespace FirstApplication
{
    class Program
    {


        static void Main(string[] args)
        {

            int getInputN = Convert.ToInt32(Console.ReadLine());

            static int getFactorial(int getInputN)
            {

                int total = 1;
                for (int i = 1; i <= getInputN; i++)
                {
                    total *= i;
                }
                return total;
            }



            Console.WriteLine(getFactorial(getInputN));

        }
    }

}

  • When you debugged through it, what did you find? (Hint - try with input of 33) – mjwills Jul 20 '21 at 03:46
  • Up until the loop is 33 the total is fine. – classicmusiclover Jul 20 '21 at 03:49
  • Really? What was the value for the input of 33? Nothing struck you as odd about that result? Because one thing it isn't is _fine_. – mjwills Jul 20 '21 at 03:51
  • 3
    Oh wow, I'm dumb. The number goes way above 2,147,483,647, so basically I shouldn't have used int – classicmusiclover Jul 20 '21 at 03:56
  • Note that the reason you are getting 0 is not because value goes above Int32.Max but because of number of twos multiplied together (as I explained in duplicate I picked). It overflows much earlier - the 33 suggested by @mjwills is a number where overflow is most obvious. I.e. if you try to compute 3^n it will never return zero... – Alexei Levenkov Jul 20 '21 at 04:26

0 Answers0