Program that determines if number is prime. How do I make it work for multiple numbers?
Mar 23, 2017 at 4:06am UTC
I have a homework assignment to see if number is prime and it needs to be able to analyze one or more numbers. It also has to display divisors of numbers that are not prime.
This is what I've got so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int num, count = 0, tester;
cout << "This program will determine if a number between 1 and 1000 is prime" << endl;
cout << "Please enter a number " ;
cin >> num;
while (num < 1 || num > 1000)
{
cout << "Enter valid number " ;
cin.clear();
cin.ignore(200, '\n' );
cin >> num;
}
for (tester = 1; tester <= num; tester++)
{
if (num % tester == 0)
count++;
}
if (count == 2)
{
cout << num << " is prime" << endl;
return (0);
}
else
cout << num << " is not prime" << endl;
if (count > 2)
cout << "Divisors: " ;
tester = 1;
do
{
if (num % tester == 0)
{
cout << tester << "\t" ;
}
tester++;
} while (tester <= num);
cout << endl;
}
It works for one number but I don't know how to make it so it can analyze more.
Mar 23, 2017 at 4:25am UTC
Well you didn't tell us how you input the 2nd number, that would help.
Mar 23, 2017 at 4:25am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bool is_prime(int num){
//lines 19--24
return count==2;
}
int main(){
//...
while (std::cin>>num){
if (is_prime(num))
std::cout << num << " is prime\n" ;
else {
//lines 33--42
}
}
}
Topic archived. No new replies allowed.