Int - number too large. How to get program to fail?

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2010-12-27T03:50:50Z Indexed on 2010/12/27 3:53 UTC
Read the original article Hit count: 192

Filed under:

Hi

Problem: How do you get a program to fail if a number goes beyond the bounds of its type?

This code below gives the wrong answer for sum of primes under 2 million as I'd used an int instead of a long.

    [TestMethod]
    public void CalculateTheSumOfPrimesBelow2million()
    {
        int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
        Assert.AreEqual(1, result); // 1,179,908,154 .. this was what I got with an int...
                                             // correct answer was 142,913,828,922 with a long
    }



public static class PrimeTester
{
    public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow)
    {
        // we know 2 is a prime number
        int sumOfPrimes = 2;
        int currentNumberBeingTested = 3;
        while (currentNumberBeingTested < maxPrimeBelow)
        {
            double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

            bool isPrime = true;
            for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
            {
                if (currentNumberBeingTested % i == 0)
                {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime)
                sumOfPrimes += currentNumberBeingTested;

            currentNumberBeingTested += 2; // as we don't want to test even numbers
        }
        return sumOfPrimes;
    }
}

© Stack Overflow or respective owner

Related posts about c#