Here is the assignment:
Write a C++ program to calculate and display the number of primes in the first 50 “chiliads”. Your results should be exactly as presented below, under testing.
Design Considerations:
I think you will find your program easier to structure and write if you break it down into functions with the following prototypes:
bool isPrime (long n);
// Returns true if n is a prime, else false
long primeCount (long x, long y);
// Returns the number of primes between x and y, inclusive.
I am having problems with the total and counter, please help
my code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
bool isPrime(long n); // Returns true if n is a prime, else false
long primeCount (long x, long y); // Returns the number of primes between x and y, inclusive
int main ()
{
int counter, total;
cout << "Start" <<setw(6) << "End" << setw(24) << "Number of Primes" << endl;
primeCount (0 , 50000);
cout << "Total primes in the first 50 chiliads:" << total << endl;
cout << "Average number per chiliad:" << counter/1 << endl;
system("pause");
}
long primeCount (long x, long y)
{
int i;
int counter = 0;
int total = 0;
bool test;
for ( int k = x; k < y; k += 1000)
{
for (i =1; i < 1000; i++ )
{
test = isPrime(i+k);
if ( test == true )
{
counter++;
total += counter;
}
}
cout << i+k-999 <<setw(10) << i+k << setw(12) << counter << endl;
counter = 0;
}}
bool isPrime (long num)
{
int j;
if(num <= 1)
return false;
for ( j = 2; j*j <= num; j++ )
if (num%j == 0)
return false;
return true;
}