File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ # # Pollard's p-1
2
+ # #
3
+ # # This file illustrates how to find a factor of an integer using
4
+ # # [Pollard's p-1 algorithm](https://en.wikipedia.org/wiki/Pollard%27s_p_%E2%88%92_1_algorithm).
5
+
6
+ import bigints
7
+ import std/ options
8
+ import std/ strformat
9
+
10
+
11
+ func pollardPMinus1(
12
+ n: BigInt,
13
+ searchLimit: BigInt,
14
+ powerBase: BigInt = 2 .initBigInt): Option[BigInt] =
15
+ # # Performs Pollard's p-1 algorithm to find a non-trivial factor of `n`.
16
+ var curPow = powerBase mod n
17
+
18
+ for k in 1 .initBigInt .. searchLimit:
19
+ curPow = curPow.powmod(k, n)
20
+ let divisor = gcd(curPow- 1 .initBigInt, n)
21
+ if divisor != 1 .initBigInt and divisor != n:
22
+ return some(divisor)
23
+
24
+ none(BigInt)
25
+
26
+
27
+ proc main() =
28
+ const someNum = " 52541208898777" .initBigInt
29
+ let result = pollardPMinus1(someNum, " 1000000" .initBigInt)
30
+ if result .isSome():
31
+ let factor = result .get()
32
+ echo fmt" { factor} is a factor of { someNum} "
33
+ assert someNum mod factor == 0 .initBigInt
34
+ else :
35
+ echo fmt" could not find a factor of { someNum} "
36
+
37
+
38
+ main()
You can’t perform that action at this time.
0 commit comments