Printing Prime and Non-Prime Numbers

Hello!

I am trying to write a script that will have the output as the following:
1 is not prime
2 is prime
3 is prime
4 is prime
N is/ is not prime

My teacher specifically wants us to write a function with prototype:
bool isPrime(int n);
that returns true if n is prime and false otherwise.


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
  #include<iostream>
using namespace std;

int main(){
  int num;
  bool prime;

  cout << "Please enter a positive integer" << endl;
  cin >> num;

  for(int i = 2; i <= num; i++){
    prime = true;
    for(int n = 2; n <= i - 1; n++){
      if(i % n == 0){
        prime = false;
      }
    }
    if(prime != false){
      cout << i << " is  prime" << endl;
    }
    else
        cout << i << "is not prime" << endl;
  }
 
  return 0;
}


I've used bool Prime instead, and I can't figure out where to go if I have to use his specific function. Any help is much appreciated!!!
Your teacher wants you to write a function that determines if given number ( int n ) is a prime or not.

Whatever code you have in the main that determines if the number is prime needs to go in the isPrime function
1
2
3
4
5
6
7
8
9
bool isPrime( int n )
{
    // Some code to determine if n is prime and return true or false
}

int main()
{
    // Some code to call isPrime()
}
Last edited on
Here's some pseudocode that may help by the way.

1
2
3
4
5
6
7
8
9
10
11
12
13
if( number is 1 )
    return false
else if( number is 2 )
    return true 
else if ( the number is even )
    return false //since all even numbers except 2 are not prime
else number is odd
    From i = 3 to and including square root of the given number
    i is incremented by 2
        if number is divisible by i
            return false

    return true; //If the loop terminates, then the number must be prime 
Last edited on
Topic archived. No new replies allowed.