Skip to content

Commit b99fb99

Browse files
authored
feat: add Pollard's p-1 example (#138)
1 parent 37a8e75 commit b99fb99

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

examples/pollard_p_minus_1.nim

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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()

0 commit comments

Comments
 (0)