0

Write a function isPrime() that takes integer n and determine whether n is a prime number or not

9th Nov 2016, 11:18 AM
Samadov Abdullokh
Samadov  Abdullokh - avatar
3 odpowiedzi
+ 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"; }
9th Nov 2016, 11:23 AM
Megatron
Megatron - avatar
+ 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
9th Nov 2016, 11:39 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 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
9th Nov 2016, 11:48 AM
Giulio Pellitta
Giulio Pellitta - avatar