0

A program to check whether a number is prime or composite?

20th Nov 2016, 9:08 AM
Mayur Kumar
Mayur Kumar - avatar
5 Respuestas
+ 3
attexx your program is wrong. It would print every odd number as prime after 1. Catch this code #include<iostream.h> #include<math.h> int main() { int no,flag=0,i=2; cout<<"Enter number"; cin>>no; while(i<=floor(sqrt(no))) { if(no%i==0) flag=1; i++; } if(no==0 || no==1) cout<<"neither prime nor composite"; else if(flag==0) cout<<"Prime number"; else cout<<"Composite number"; return 0; }
20th Nov 2016, 12:51 PM
Megatron
Megatron - avatar
+ 2
@Eita Stein Thanks for the comment. This method is called sieve of Eratosthenes. This is one of the fast methods but there is one more method faster than this called wheel sieve but I quite don't understand it.
20th Nov 2016, 3:40 PM
Megatron
Megatron - avatar
+ 1
basicaly what megatron wrote is the best answer if u dont want to enter all the mathematics involved (if there is a number x that x>sqrt(no) and no%x==0 it means there is a number y where x*y = no and y<sqrt(no) this is why its enough to go till u reach sqrt(no) ) u can use the same code but write in the loop while(i<no)
20th Nov 2016, 1:22 PM
Ethan
Ethan - avatar
+ 1
@megatron the comment was mainly for mayur kumar but i am glad u enjoyed it as well ;) i am not very strong woth names XD but i understand the mathematical principle behind it so i dont mind i also dont know the other method you were talking about but the simplest way to speed up the code would be: check if no%2==0 than start from the while loop from i=3 and increase i by 2 each time (you dont have to check the even numbers after you checked 2 since 2 is the only even prime number)
20th Nov 2016, 3:51 PM
Ethan
Ethan - avatar
0
According to (wikipedia) definition a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. Numbers 0 and 1 are neither prime nor composite numbers. The following C++ code could be used to check whether a number is prime or composite: #include <iostream> int main() { int number; cout << "Please enter an integer number: "; cin >> number; if (number == 0 || number == 1) cout << "The number is neither prime nor composite."; else { if (number % 2 != 0) cout << "The Number is prime number."; else cout << "The number is composite."; } return 0; }
20th Nov 2016, 11:24 AM
attexx
attexx - avatar