0
How to check whether a num is prime or not
5 Answers
+ 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;
}
+ 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;
}
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
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.
- 3
Heyy