Am trying to find all prime numbers between two given numbers and sum the primes up.
I have this loop that does the prime number detection correctly.
However, for some reason I don’t know how to sum all the primes.
int a,b,i,j,sum=0;
do
{ cout << "Enter a number: ";
cin >> a;
if (a < 4 || a > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (a < 4 || a > 1000000);
do
{ cout << "Enter a second number: ";
cin >> b;
if (b < 4 || b > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (b < 4 || b > 1000000);
if (a > b)
{ int hold;
hold = b;
b = a;
a = hold;
}
cout << "The prime numbers between " << a << " and " << b << " inclusive are: " << endl;
//int sum;
for (i = a; i <= b; i++)
{
for (j = 2; j <= i; j++) // Changed the < to <=, and got rid of semicolon
{
if (!(i%j)&&(i!=j)) break;
if (j==i)
{
cout << i << endl;
sum += i;
cout << sum ;
}
}
}
The variable sum gives me rubbish results.
It is impossible to know without the exact details but two most likely possibilities are:
sumwas not initialized to 0 prior to usagesum, and the range.EDIT:
The editted code works for me, for small ranges (note that for larger ranges, one should also consider issue #2).
You might be misreading the results, try adding
endltocout << sum ;