-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimality.hpp
52 lines (40 loc) · 1.03 KB
/
primality.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
// https://en.wikipedia.org/wiki/Primality_test
#ifndef FORFUN_PRIMALITY_HPP_
#define FORFUN_PRIMALITY_HPP_
#include <cmath>
#include <concepts>
#include <utility>
namespace forfun::primality {
template <std::unsigned_integral UInteger>
/*constexpr*/ inline auto
is_prime(UInteger const n) noexcept(noexcept(std::sqrt(std::declval<UInteger>())
)) -> bool
{
if (n < UInteger{2U})
{
return false;
}
if (n == UInteger{2U})
{
return true;
}
if ((n & UInteger{1U}) == UInteger{0U})
{
return false;
}
UInteger const r{static_cast<UInteger>(std::sqrt(n))};
for (UInteger i{3U}; i <= r; ++i)
{
if (((i & UInteger{1U}) != UInteger{0U}) && ((n % i) == UInteger{0}))
{
return false;
}
}
return true;
}
} // namespace forfun::primality
#endif // FORFUN_PRIMALITY_HPP_