I'm getting numbers like 9 and 15 also prime by using this code . pls find the error in the code and if possible Pls edit my code to find the error Here is the code--
`#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number : ";
cin>>n;
int flag=0;
//to check prime check from 2 to n
for(int i=2;i<=n;i )
{
if(n%2==0)
{
cout<<n<<" is a non-prime number";
flag ;
break;
}
else
{
if(flag==0)
{
cout<<n<<" is a prime number";
break;
}
}
}
return 0;
}
CodePudding user response:
Your check logic is flawed as you are checking against %2
, you should check against %i
. I've also added a little optimization as you only need to check up until n/2
.
To check if a number is prime:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number : ";
cin>>n;
bool prime=true;
//to check prime check from 2 to n
for(int i=2;i<=n/2;i )
{
if(n%i==0)
{
prime = false;
break;
}
}
if (prime)
cout<<n<<" is a prime number";
else
cout<<n<<" is a non-prime number";
return 0;
}
CodePudding user response:
Your code is not checking if the number is prime or not instead it just check if all the number from 2 to n are even or odd and as the value of i become an odd number (which is 3, just after its first iteration) the code executes these lines
cout<<n<<" is a prime number";
flag ;
Also what is the point of
flag = 0
if you are using break for terminating the loop.
You must be trying to write something like this
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number : ";
cin>>n;
int flag=0;
for(int i=2;i<=n;i )
{
if(n%i==0)
{
cout<<n<<" is a non-prime number";
flag ;
break;
}
}
if(flag==0)
{
cout<<n<<" is a prime number";
break;
}
return 0;
}
Also to make this code better write
for(int i=2;i<=sqrt(n);i )
instead