0

How to check whether a num is prime or not

1st Sep 2016, 4:27 PM
jasmine
5 Respuestas
+ 4
#include <math> bool isPrime(unsigned int n) { int i; if (n < 2) { return false; } for (i = 2; i <= sqrt(n); i++) { if (n % i == 0) { return false; } } return true; }
1st Sep 2016, 4:59 PM
Zen
Zen - avatar
+ 1
#include <iostream> using namespace std; int main() { int i,n,prm=0; cin >>n; for(i=2;i<n/2;i++){ if (n%i==0) prm=1; break; } if (prm==1) { cout <<n<<"\t is a composite number"<<endl; } else { cout <<n<<"\t is a prime number"<<endl; } return 0; }
1st Sep 2016, 4:46 PM
Vjmsd
Vjmsd - avatar
0
use numbers from 2 to sprt n or just use primes that you record which are less than sqrt n to get fast speed
1st Sep 2016, 10:52 PM
Tipwheal
Tipwheal - avatar
0
basically the logic behind knowing if a number is prime or not we need atleast 2 remainders of it that it one by itself and the other.
2nd Sep 2016, 11:59 AM
Yash Mohta
Yash Mohta - avatar
- 3
Heyy
1st Sep 2016, 5:22 PM
Aniket Shrouti
Aniket Shrouti - avatar