0

What is the logic behind prime number program in c ++?????

19th Feb 2017, 7:29 AM
prateek verma
prateek verma - avatar
7 odpowiedzi
+ 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; }
19th Feb 2017, 7:45 AM
Megatron
Megatron - avatar
+ 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
19th Feb 2017, 7:37 AM
Megatron
Megatron - avatar
+ 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.
19th Feb 2017, 8:53 AM
Megatron
Megatron - avatar
+ 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"
19th Feb 2017, 9:32 AM
Huegel
Huegel - avatar
0
plz post it
19th Feb 2017, 7:38 AM
prateek verma
prateek verma - avatar
0
can't understand the condition you have mentioned in for loop
19th Feb 2017, 7:48 AM
prateek verma
prateek verma - avatar
0
logic will be same in every programming language. it is syntax which changes.
19th Feb 2017, 8:14 AM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar