Skip to content

Commit 8b49dce

Browse files
Adde Pollards Rho algorithm (TheAlgorithms#365)
1 parent 650ee47 commit 8b49dce

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using Algorithms.Other;
2+
using NUnit.Framework;
3+
4+
namespace Algorithms.Tests.Other
5+
{
6+
public class PollardsRhoFactorizingTests
7+
{
8+
[TestCase(8051, 97)]
9+
[TestCase(105, 21)]
10+
[TestCase(253, 11)]
11+
[TestCase(10403, 101)]
12+
[TestCase(187, 11)]
13+
public void SimpleTest(int number, int expectedResult)
14+
{
15+
var result = PollardsRhoFactorizing.Calculate(number);
16+
Assert.AreEqual(expectedResult, result);
17+
}
18+
}
19+
}
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using Algorithms.Numeric.GreatestCommonDivisor;
3+
4+
namespace Algorithms.Other
5+
{
6+
/// <summary>Implementation of the Pollard's rho algorithm.
7+
/// Algorithm for integer factorization.
8+
/// Wiki: https://en.wikipedia.org/wiki/Pollard's_rho_algorithm.
9+
/// </summary>
10+
public static class PollardsRhoFactorizing
11+
{
12+
public static int Calculate(int number)
13+
{
14+
var x = 2;
15+
var y = 2;
16+
var d = 1;
17+
var p = number;
18+
var i = 0;
19+
var gcd = new BinaryGreatestCommonDivisorFinder();
20+
21+
while (d == 1)
22+
{
23+
x = Fun_g(x, p);
24+
y = Fun_g(Fun_g(y, p), p);
25+
d = gcd.FindGcd(Math.Abs(x - y), p);
26+
i++;
27+
}
28+
29+
return d;
30+
}
31+
32+
private static int Fun_g(int x, int p)
33+
{
34+
return (x * x + 1) % p;
35+
}
36+
}
37+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ find more than one implementation for the same objective but using different alg
192192
* [Decisions Convolutions](./Algorithms/Other/DecisionsConvolutions.cs)
193193
* [Welford's Variance](./Algorithms/Other/WelfordsVariance.cs)
194194
* [Julian Easter](./Algorithms/Other/JulianEaster.cs)
195+
* [Pollard's Rho](./Algorithms/Other/PollardsRhoFactorizing.cs)
195196
* [Problems](./Algorithms/Problems)
196197
* [Stable Marriage](./Algorithms/Problems/StableMarriage)
197198
* [Gale-Shapley](./Algorithms/Problems/StableMarriage/GaleShapley.cs)

0 commit comments

Comments
 (0)