Built in prime checking function
There is no C++ "build-in" function, but you can resolve this with compile time efficiency using metaprogramming.
template <int i>
struct D
{
D(void *);
operator int();
};
template <int p, int i>
struct is_prime
{
enum { prim = (p%i) && is_prime<(i>2?p:0), i>::prim };
};
template <int i>
struct Prime_print
{
Prime_print<i-1> a;
enum { prim = is_prime<i,i-1>::prim };
void f() { D<i> d = prim; }
};
struct is_prime<0,0> { enum { prim = 1 }; };
struct is_prime<0,1> { enum { prim = 1 }; };
struct Prime_print<2>
{
enum { prim = 1 };
void f() { D<2> d = prim; }
};
void foo()
{
Prime_print<10> a;
}
Hope it helps
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
Short answer: no, there's no such function.
The only time the word "prime" is used in the standard is a footnote in 26.5.3.2, which is where the mersenne_twister_engine
class template is described. The footnote says:
274) The name of this engine refers, in part, to a property of its period: For properly-selected values of the parameters, the period is closely related to a large Mersenne prime number.
If such function existed, the standard would contain more occurrences of that word, as it would use it to describe the behavior of that function.