Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add rho-Pollard example #129

Merged
merged 6 commits into from
Sep 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions examples/pollard_rho.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
## Pollard's rho algorithm
##
## This file illustrates how to find a factor of an integer using
## [Pollard's rho algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm).

import bigints
import std/options
import std/strformat


func pollardRho(
n: BigInt,
polynomial: proc(x: BigInt): BigInt {.noSideEffect.},
initialValue: BigInt = 2.initBigInt): Option[BigInt] =
## Performs Pollard's rho algorithm to find a non-trivial factor of `n`.
func polynomialMod(x: BigInt): BigInt =
polynomial(x) mod n

var
turtle = initialValue
hare = initialValue
divisor = 1.initBigInt

while divisor == 1.initBigInt:
turtle = polynomialMod(turtle)
hare = polynomialMod(polynomialMod(hare))
divisor = gcd(turtle - hare, n)

if divisor != n:
some(divisor)
else:
none(BigInt)


func somePolynomial(x: BigInt): BigInt =
x * x + 1.initBigInt


proc main() =
const someNum = "44077431694086786329".initBigInt
let result = pollardRho(someNum, somePolynomial)
if result.isSome():
let factor = result.get()
echo fmt"{factor} is a factor of {someNum}"
assert someNum mod factor == 0.initBigInt
else:
echo fmt"could not find a factor of {someNum}"


main()