【问题标题】:Another Pollard Rho Implementation另一个 Pollard Rho 实现
【发布时间】:2015-07-30 21:18:07
【问题描述】:

为了解决 Euler 项目 (https://projecteuler.net/problem=3) 的第三个问题,我决定实现 Pollard 的 Rho 算法(至少是其中的一部分,我计划稍后包含循环)。奇怪的是,它适用于以下数字:82123(因子 = 41)和 16843009(因子 257)。但是,当我尝试项目 Euler 编号:600851475143 时,当最大素数为 6857 时,我最终得到 71。这是我的实现(对不起,代码墙和缺少类型转换):

#include <iostream>
#include <math.h>
#include <vector>

using namespace std;

long long int gcd(long long int a,long long int b);
long long int f(long long int x);

int main()
{
long long int i, x, y, N, factor, iterations = 0, counter = 0;
vector<long long int>factors;

factor = 1;
x = 631;
N = 600851475143;
factors.push_back(x);

while (factor == 1)
{
    y = f(x);
    y = y % N;
    factors.push_back(y);
    cout << "\niteration" << iterations << ":\t";
    i = 0;
    while (factor == 1 && (i < factors.size() - 1))
    {
        factor = gcd(abs(factors.back() - factors[i]), N);
        cout << factor << " ";
        i++;
    }
    x = y;
    //factor = 2;
    iterations++;
}

system("PAUSE");
return 0;
}

long long int gcd(long long int a, long long int b)
{
    long long int remainder;
    do
    {
    remainder = a % b;
    a = b;
    b = remainder;
    } while (remainder != 0);
    return a;
}

long long int f(long long int x)
{
//x = x*x * 1024 + 32767;
x = x*x + 1;
return x;
}

【问题讨论】:

  • 那么 71 是一个因素,那么问题是什么? Pollards Rho 从未承诺给你最大的因素

标签: algorithm primes factorization


【解决方案1】:

Pollard 的 rho 算法没有任何保证。它不能保证找到最大的因素。它不保证它找到的任何因素都是素数。它甚至不能保证找到一个因素。 rho 算法是概率性的;它可能会找到一个因素,但不一定。由于您的函数返回一个因子,因此它可以工作。

也就是说,您的实现不是很好。不必存储函数的所有先前值,并每次通过循环计算 gcd。这是该函数更好版本的伪代码:

function rho(n)
    for c from 1 to infinity
        h, t := 1, 1
        repeat
            h := (h*h+c) % n # the hare runs ...
            h := (h*h+c) % n # ... twice as fast
            t := (t*t+c) % n # as the tortoise
            g := gcd(t-h, n)
        while g == 1
        if g < n then return g

此函数返回 n 的单个因子,它可以是素数或合数。它只存储随机序列的两个值,并在找到一个循环时停止(当 g == n 时),以不同的随机序列重新开始(通过递增 c)。否则它会一直运行,直到找到一个因子,只要将输入限制为 64 位整数,这不会花费太长时间。通过将 rho 应用于剩余的辅因子来查找更多因子,或者如果找到的因子是复合因子,则在找到所有素因子时停止。

顺便说一句,您不需要 Pollard 的 rho 算法来解决 Project Euler #3;简单的试除法就足够了。这个算法找出一个数的所有质因数,你可以从中提取出最大的:

function factors(n)
    f := 2
    while f * f <= n
        while n % f == 0
            print f
            n := n / f
        f := f + 1
    if n > 1 then print n

【讨论】:

  • 您好,感谢您的帮助!我将不得不阅读更多关于算法并尝试你的实现。
猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多