Answered by:
Prime Numbers
Question

I know that this may not be the fastest way to solve find the sum of all prime numbers under 2000000 but I dont understand why it is not working
#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; int main() { int isPrime; int total = 0; for(int i=1;i<2000000;i++) { for(int j=2;j<i;j++) { isPrime = i % j; if (isPrime == 0) { if (isPrime == j) { total += i; break; } break; } } } cout << total << endl; system("pause"); return 0; }
Answers

What does this accomplish?
if (isPrime == 0)
{
if (isPrime == j) // means: if(j == 0)
Since j can never be less than 2 ...
 Wayne
 Marked as answer by Wesley Yao Friday, July 10, 2009 3:40 AM

You are going to have to write a functional prime generator first. The algorithm is over 2000 years old.
Hans Passant. Marked as answer by Wesley Yao Friday, July 10, 2009 3:39 AM
All replies



What does this accomplish?
if (isPrime == 0)
{
if (isPrime == j) // means: if(j == 0)
Since j can never be less than 2 ...
 Wayne
 Marked as answer by Wesley Yao Friday, July 10, 2009 3:40 AM




I may not be answering your question but a couple of points to make the search faster. You don't have to check till the number (2000000). It's just enough to check till the square root of 2000000. In the inner loop you first check if it is divisible by 2 and then check with odd numbers only like 3, 5, 7 etc.
«_Superman_» 
This is what I am trying to do.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

You are going to have to write a functional prime generator first. The algorithm is over 2000 years old.
Hans Passant. Marked as answer by Wesley Yao Friday, July 10, 2009 3:39 AM

A simplifying strategy here would be to write a separate function to test for primeness.
bool IsPrime(int i);
int main()
{
int total = 0;
for(int i=1;i<2000000;i++)
{
if (IsPrime(i))
{
total += i;
}
cout << total << endl;
return 0;
}
bool IsPrime(int i)
{
// your code here
}
David Wilkinson  Visual C++ MVP Edited by davewilk Saturday, July 4, 2009 11:44 AM formatting