Reputation: 103
I keep getting the wrong answer of 1179908154. At first I blamed it on my summation variable being type int, rather than long. I gave it long type but I get the same answer. Thoughts?
// Project Euler
// Problem 10
#include <iostream>
#include <cmath>
using namespace std;
void main()
{
int p = 3;
long sum = 2;
bool isPrime;
for (p; p < 2000000; p++)
{
isPrime = true;
for (int i = 2; i <= sqrt(static_cast<double>(p)); i++) // cast into double for sqrt function
{
if (p % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
cout << p << endl; // show each prime
sum += p; // add prime to sum
}
}
cout << sum << endl; // show sum
system("pause");
}
Upvotes: 0
Views: 810
Reputation: 171
Maybe on your platform the long is not enough to hold the value too. Try a long long instead.
Upvotes: 2
Reputation: 1
When putting the bounds on your for loop, you should check numbers up until sqrt(p) + 1. You can get floating point errors when calculating the square root (it might underestimate it slightly), so it's possible that some potential factors are not checked in the loop.
Upvotes: 0