Search code examples
c#divide-by-zero

C# % throws DivideByZeroException


    public static List<int> getDenoms(long n)
    {
        List<int> result = new List<int>();
        for (int i = 1; i < n; i++)
        {
            if (n % i == 0)
            {
                result.Add(i);
            }
        }
        return result;
    }

    public static int getHighestPrime(List<int> seq)
    {
        int currentHigh = 1;
        foreach (int number in seq)
        {
            List<int> temp = getDenoms(number);
            if (temp.Count == 1)
            {
                if (number > currentHigh)
                {
                    currentHigh = number;
                }
            }
        }
        return currentHigh;
    }

I have the current code going in C#. So, I have the two methods. In the getDenoms method, I assumed that the statement n%i would not throw any errors since i is greater than or equal to 1, but it does indeed throw that error.

I used the two methods in the following manner:

        Console.WriteLine(getHighestPrime(getDenoms(600851475143)));

Any insight on why the code is throwing that error?


Solution

  • The reason is that 600851475143 is too big for an int!

    Your looping variable i is an int, but you compare it to a long. 600851475143 is greater than int.MaxValue, so i eventually overflows and restarts at int.MinValue. Then it increases until it's 0 again and voilá:

    DivideByZeroException

    To solve this change the type of your loop variable to long, too:

    for (long i = 1; i < n; i++)