FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm-examples/cpp-algorithm/src/math/miller_rabin.cpp at main · codejsha/algorithm-examples · GitHub
codejsha
/
algorithm-examples
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
math
/
miller_rabin.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
81 lines (70 loc) · 1.45 KB
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
math
/
miller_rabin.cpp
Copy path
File metadata and controls
81 lines (70 loc) · 1.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#
include
"
miller_rabin.h
"
#
include
<
random
>
auto
MillerRabin::ModularExponentiation
(
int
base,
int
exponent,
const
int
mod) -> int
{
int
result =
1
;
while
(exponent >
0
)
{
if
(exponent %
2
==
1
)
{
result = (result * base) % mod;
}
exponent /=
2
;
base = (base * base) % mod;
}
return
result;
}
auto
MillerRabin::Witness
(
int
exponent,
const
int
number) -> bool
{
std::random_device rd;
std::mt19937
generator
(
rd
());
std::uniform_int_distribution
distribution
(
2
, number -
1
);
const
int
random =
distribution
(generator);
int
x =
ModularExponentiation
(random, exponent, number);
if
(x ==
1
|| x == number -
1
)
{
return
true
;
}
while
(exponent != number -
1
)
{
x = (x * x) % number;
exponent *=
2
;
if
(x ==
1
)
{
return
false
;
}
if
(x == number -
1
)
{
return
true
;
}
}
return
false
;
}
auto
MillerRabin::MillerRabinPrimalityTest
(
const
int
number,
const
int
repeats) -> bool
{
if
(number <
2
)
{
return
false
;
}
if
(number ==
2
)
{
return
true
;
}
if
(number %
2
==
0
)
{
return
false
;
}
int
d = number -
1
;
while
(d %
2
==
0
)
{
d /=
2
;
}
for
(
int
i =
0
; i < repeats; ++i)
{
if
(!
Witness
(d, number))
{
return
false
;
}
}
return
true
;
}
Back
|
FazBrowse Home
|
New Git URL