Int - number too large. How to get program to fail?
- by Dave
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;
}
}