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 2 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
46 changes: 46 additions & 0 deletions examples/rho_pollard.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
## Rho-Pollard
##
## This file illustrates how to find a factor of an integer using the
## [rho-Pollard algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm).
vil02 marked this conversation as resolved.
Show resolved Hide resolved

import bigints
import std/options
import std/strformat


func rhoPollard(
n: BigInt,
nextIteration: proc(x: BigInt): BigInt {.noSideEffect.},
initialValue: BigInt = 2.initBigInt): Option[BigInt] =
## performs the rho-Pollard search
func nextIterationMod(x: BigInt): BigInt =
return nextIteration(x) mod n
var
turtle = initialValue
hare = initialValue
divisor = 1.initBigInt

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

if divisor != n:
return some(divisor)
vil02 marked this conversation as resolved.
Show resolved Hide resolved


func somePoly(number: BigInt): BigInt =
return number*number+1.initBigInt
vil02 marked this conversation as resolved.
Show resolved Hide resolved


proc main() =
const someNum = "44077431694086786329".initBigInt
let result = rhoPollard(someNum, somePoly)
vil02 marked this conversation as resolved.
Show resolved Hide resolved
if result.isSome():
echo fmt"{result.get()} is a factor of {someNum}"
assert someNum mod result.get() == 0.initBigInt
vil02 marked this conversation as resolved.
Show resolved Hide resolved
else:
echo fmt"could not find a factor of {someNum} using rho-Pollard algorithm"
vil02 marked this conversation as resolved.
Show resolved Hide resolved


main()