0
What is the logic behind prime number program in c ++?????
7 Respostas
+ 3
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int no,flag=0,i=2;
cout<<"Enter number\n";
cin>>no;
if(no==0 || no==1)
{
cout<<"neither prime nor composite";
return 0;
}
else if (no%2==0&&no!=2)
{
cout<<" composite";
return 0;
}
for(i=3;i<=floor(sqrt(no));i+=2)
{
if(no%i==0)
{
cout<<"composite number";
return 0;
}
}
cout<<"Prime number";
return 0;
}
+ 2
A number can be tested for being prime in many ways.
A number is prime if it is not divisible by any natural number except 1 before it.
The code can be shortened using different constraints.
If you are having any difficulty ask, I will post the code.
For some advanced methods check
wheel sieve
sieve of erastosthenes
+ 2
A number can be written as
p*q=num
If p is one factor the smaller one
then q will be larger one and would lie beyond sqrt(num)
So it is sufficient to check till sqrt(num)
sqrt->return square root of num
Floor->returns 1 if number passed is from 1 to 1.9999999999....
google sieve of erastosthenes for more clarification.
+ 2
You made a mistake at
else if (no%2==0)
{
cout<<" composite";
return 0;
}
If I enter 2, the output is "composite", but it should be"prime number"
0
plz post it
0
can't understand the condition you have mentioned in for loop
0
logic will be same in every programming language. it is syntax which changes.