0
Write a function isPrime() that takes integer n and determine whether n is a prime number or not
3 ответов
+ 2
#include<math.h>
void isprime(int no)
{
int i=2;
int flag=0;
while(i<=floor(sqrt(no)))
/*
Fastest method I know
comes from
Sieve of Eratosthenes
*/
{
if(no%i==0)
{ flag=1; break;}
i++;
}
if(flag==0)
cout<<"Prime number";
}
+ 1
#include <iostream>
using namespace std;
bool isprime(int i)
{
int j=2,flag;
while(j<=i-1)
{
if(i%j==0){
flag=0;
break;
}
j++;
}
if(flag){
return true;
}
return false;
}
int main() {
cout << isprime(2) << endl;
return 0;
}
output is
1 //true
+ 1
The wheel sieve is much faster than the sieve of Erathosthenes. As for prime testing, there is an algorithm AKS which is the only one (up to variants / optimizations) which runs in polynomial time. Here's an implementation in C: https://rosettacode.org/wiki/AKS_test_for_primes#C