Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in prime checking function

Tags:

c++

Does C++ have any built in function to check if the number is prime or not. If yes, then in which library?

Below is my implementation. But was just looking if there is any built in function. Searching on Google just gives user based implementations.

int isprime(int N){
    if(N<2 || (!(N&1) && N!=2))
        return 0;
    for(int i=3; i*i<=N; i+=2){
        if(!(N%i))
            return 0;
    }
    return 1;
}
like image 528
Devender Goyal Avatar asked Jun 05 '12 12:06

Devender Goyal


People also ask

Which inbuilt function can be used to check if the number is prime or not?

The isPrime(int n) method is used to check whether the parameter passed to it is a prime number or not. If the parameter passed is prime, then it returns True otherwise it returns False.

Is prime built in function in Python?

isprime(n): It tests if n is a prime number (True) or not (False). primerange(a, b): It generates a list of all prime numbers in the range [a, b). randprime(a, b): It returns a random prime number in the range [a, b). primepi(n): It returns the number of prime numbers less than or equal to n.

What is prime checker?

Simple methods. The simplest primality test is trial division: given an input number, n, check whether it is evenly divisible by any prime number between 2 and √n (i.e. that the division leaves no remainder). If so, then n is composite. Otherwise, it is prime.

Which inbuilt function can be used to check if the number is prime or not in C?

Method 3: Check whether a number is prime or not Using sqrt(n) Function.


1 Answers

No, there's no built-in function that checks for prime.

The solution you posted could be improved on: the i*i can be avoided if you only calculate the square root of N once.

If you know the range of the number you want to check, you can use a sieve and a map, as to not calculate repeatedly - http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

like image 97
Luchian Grigore Avatar answered Sep 24 '22 15:09

Luchian Grigore