I know there are tons of posts on this, I think I'm on the right track with this, but I can't quite get it to work. I can't figure out how to get the range of primes to print. I'd appreciate any input I can get, sorry about the indenting.
main() keeps doing the following, until user enters a 0 or a negative number:
• Ask user to enter a number;
• If it is positive, print all the prime numbers between 1 and it; when there’s no prime number, print “none; ( A prime number is a whole number that can only be divided by 1 and itself, i.e., 2, 3, 5, 7, 11, 13, 17, 23, ….)
• Print the max of these prime numbers; or print “none when there’s no prime.
The calling relation should be: main() calls printPrimes() and getMaxPrime();
printPrimes() and getMaxPrime() calls isPrime() .
My Code:
#include <iostream>
#include <math.h>
using namespace std;
/* function isPrime (int num) finds out whether the input integer num is a prime number or not
*/
bool isPrime (int num)
{
for (int fac = 2; fac <= num; fac++)
if (num % fac == 0) return 0;
return 1;
}
/* function printPrimes (int num) prints all the prime numbers between 1 and num
*/
void printPrimes (int num)
{
int number = 1;
while(number <= num)
{
++number;
if (isPrime(number))
cout << number<<" ";
}
}
/* function getMaxPrime(int num) returns the greatest prime number between 1 and num. if there is no prime number between 1 and num, getMaxPrime() should return a 0.
*/
int getMaxPrime (int num)
{
int maxCount = 0;
for (int count = 1; count <= num; count++)
{
if (isPrime(count))
maxCount = count;
}
return int (maxCount);
}
int main ()
{
int number;
do
{
cout <<endl<<endl
<<"Please enter a number, 0 or negative to stop :";
cin >> number;
if (number > 0)
{
cout << "All the prime numbers between 1 and "<< number<<" are: "<< endl;
printPrimes(number);
cout << "The max prime is :" ;
int maxPrime = getMaxPrime(number);
if (maxPrime==0) cout <<"none.";
else cout << maxPrime;
}
} while (number>0);
return 0;
}