-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprime.h
More file actions
executable file
·52 lines (48 loc) · 1.15 KB
/
prime.h
File metadata and controls
executable file
·52 lines (48 loc) · 1.15 KB
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
#pragma once
namespace cs
{
/**
* @brief Returns true if specified number @p num is prime.
* Complexity: O(sqrt(num))
* @param num - integer number tested for primality.
* @return true if specified number @p num is prime, false otherwise.
*/
inline bool IsPrime(int num)
{
if (num <= 1)
return false;
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
return false;
}
return true;
}
/**
* @brief Returns a prime number greater than given @p x.
* @param x
* @return prime number greater than given @p x.
*/
inline int NextPrime(int x)
{
while (true)
{
if (IsPrime(++x))
return x;
}
}
/**
* @brief Returns a prime number smaller than given @p x.
* @param x
* @return prime number smaller than given @p x.
*/
inline int PreviousPrime(int x)
{
while (x > 1)
{
if (IsPrime(--x))
return x;
}
return 0;
}
} // namespace cs