I need help about Prime number

Write your question here.

#include <iostream>
#include <math.h>
using namespace std;

bool prime(int);

int main()
{
int a=0;
do {
cout<<"please enter a number larger than two: ";
cin>>a;
} while (a <= 2);
for(int number = 2; number <= a; number++){
bool isPrime = prime(number);
if (isPrime)
{
cout<< endl << number << endl;
}
}
}

bool prime(int number)
{

for(int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0){
return false;
}
}
return true;

}

So this is my code. But I want to change my output . Instead of giving me the list of prime number I want it to change into True or False
Example:
Input 5
Output True

Input 10
Output False

I do some searching on the internet but I have no idea how to cover it into my code without doing it again
I believe you want something like this:

bool isPrime = prime(number);
cout << endl << number << " - " << boolalpha << isPrime << endl;

Removed your if(isPrime) because it seems you want to print out all numbers. "boolalpha" changes 0 and 1 to false and true.
Last edited on
Or just replace the for-loop with this line:
 
    cout << boolalpha << prime(a) << endl;
so after I change it. It gives me this
Input: 5
Output:
2- true
3- true
4- false
5 -True

But It doesnt what I mean. I want it is like Prime number checker
like If u enter 5 it will give you the answer " True it is prime number"
or if u enter 6 it will give you " False it is not prime number"
That output shows that you did not remove the for-loop.
ohm ok I got it but now the Out put is like
Input 5
Output
true
true
true

Input 10
Output
false
false
false
false
false
false
false
false

How can I make it only 1 line
Looks like you still did not take out this for loop:
1
2
3

for(int i = 2; i <= sqrt(number); i++)
{
The extra lines come from some sort of loop. Just get rid of the loop and keep the code which does what you need.
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
#include <iostream>
#include <cmath>

using namespace std;

bool prime(int);

int main()
{
    int a=0;
    do {
        cout<<"please enter a number larger than two: ";
        cin>>a;
    } while (a <= 2);

    cout << boolalpha << prime(a) << endl;
}

bool prime(int number)
{
    for (int i = 2; i <= sqrt(double(number)); i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }
    return true;
}
Thank you so much I love u
Topic archived. No new replies allowed.