I want to make a program that reads any positive integer the user inputs, and outputs whether it's a prime number or not, without using bool variables.I think I got the logic right but the program still doesn't work properly, when I type 3 or 5 it outputs nothing, and when I input any number that ends with 5 it will output "Prime number" no matter what the number is. But when I input a number like "27" it's not considered a prime number.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{ int n;
cout<<"Please enter an integer"<<endl;
cin>>n;
if (n==2) cout<<"Prime number"<<endl;
if (n%2==0) cout<<"Not a prime number"<<endl;
if (n%2!=0)
{
for (int i=3; i<=sqrt (double(n)); i+=2)
{
if (n%i!=0) cout<<"Prime number"<<endl;
if (n%i==0)
cout<<" not a prime number "<<endl;break;
#include<iostream>
#include<cmath>
usingnamespace std;
int main()
{ int n;
cout<<"Please enter an integer"<<endl;
cin >>n;
if (n==2)
{
cout<<"Prime number"<<endl;
system ("pause");
return 0;
}
if (n%2==0)
{
cout<<"Not a prime number"<<endl;
system ("pause");
return 0;
}
for (int i=3; i<=sqrt (double(n)); i+=2)
{
if (n%i==0)
{
cout<<" not a prime number "<<endl;
system ("pause");
return 0;
}
}
cout<<"Prime number"<<endl;
system ("pause");
return 0;
}
The biggest problem was line 15. It needed to be moved outside of the for loop. I also removed some redundancies such as the extra if statement on line 12.
well, when n = 3 or 5 (7 shouldn't work either, I believe), sqrt(n) < 3, so your program never enters the for loop. Also, your break is not in any if. It breaks every time. I suppose your code can only say that numbers >= 9 and divisible by 3 are not prime .But that's irrelevant. You're overcomplicating things with your optimizations.
Firstly, check if the number = 1. 1 is not prime. Then do a for(int i = 2; i <= sqrt(n); i++) loop. In the loop, if n % i == 0, the number is not prime. Print that and break out of the loop. You should also set a variable to indicate that n is not prime. If you don't want to, you could add return 0 instead of break, but a variable is a lot cleaner.
You can only tell if n is prime if it cannot be divided by any i in the loop. You cannot tell if n is prime inside it. After the for loop, if your variable (if you're using it) isn't set, number is prime.