I'm working on a program to output the number of prime numbers in the first 50,000 numbers, in increments of 1000. Does anyone know what is wrong with this code?
#include <iostream>
constint CHILIADS = 50;
bool isPrime (long n);
long primeCount (long x, long y);
usingnamespace std;
int main()
{
cout << setw(10) << left << "Start" << setw(10) << "End" << setw(24) << "Number of Primes" << endl;
primeCount (0, 50000);
return 0;
}
// Determines whether the number is prime
bool isPrime (long n)
{
int a;
if (n == 1)
{
returnfalse;
}
for (a = 2; a <= (n / 2); a++)
{
if ((n % a) == 0)
{
returnfalse;
}
returntrue;
}
}
// Counts and organizes the prime numbers using the isPrime function
long primeCount (long x, long y)
{
bool prime;
int b;
int c = 1000;
int counter = 0;
int totalSum = 0;
for (b = x; b <= y; b++)
{
prime = isPrime (b);
if (prime == true)
{
counter++;
}
if (b == c)
{
cout << setw(10) << left << (b - 999) << setw(10) << left << b << setw(12) << counter << endl;
totalSum = totalSum + counter;
counter = 0;
c = c + 1000;
}
}
cout << endl << "Total primes in the first 50 chiliads: " << totalSum << endl;
cout << "Average number per chiliad: " << totalSum / CHILIADS << endl;
}
While looping through all of the numbers you need to have "return true" on the outside of the for loop for it to work correctly. Or else it will return true after the first check every time.
1 2 3 4 5 6 7 8 9
for (a = 2; a <= (n / 2); a++)
{
if ((n % a) == 0)
{
returnfalse;
}
}
returntrue;