使用Pollard rho算法计算两个大整数的最小公倍数

来源:互联网 发布:网络作家富豪榜 2016 编辑:程序博客网 时间:2024/05/01 16:45

本文主要介绍基本思路和具体的python代码实现

Pollard rho算法基本思路

Created with Raphaël 2.1.0输入n取种子X0 = 2 F(x) = x ^ 2 + 1x(i+1) = F(x(i))x < n?计算p = gcd(x(i) - x(j), n) (i != j)对p去重,排序p > 1, 保留, p = 1,去除。输出List_pyesno

1、F(x)=x^2+a 中的a可以试情况而定,一般取1,但尽量不要取0和2;
2、种子默认取2,原则上不小于2;
3、Pollard算法可以快速获取数n的几个因子,但这些因子不是n的质因子,也不是n的所有因子;
4、通过限定x>n , 规避循环问题。

使用Pollard rho算法求最小公倍数的基本思路

Created with Raphaël 2.1.0输入a, b计算Pollard(a), Pollard(b)计算a / Pollard(a), b / Pollard(b)将前两步得到的所有因子合并在一起,去重,排序,得到列表factor计算LCM = a * b(LCM / factor[i] % a == 0) and (LCM / factor[i] % b == 0)?LCM = LCM / factor[i]输出LCMyesno

本方法只经过有限验证,不保证一定正确,仅做参考。

具体python2.7代码如下:

# !/user/bin/env python# -*-coding: utf-8 -*-'''Using Pollard Pho factoring to find LCM(a, b)seed = 2, f(x) = x^2 + 1'''from fractions import gcd# find the factors of n with large powerdef Pollard(n):    # generate the list(List_x) of x    x = 2    f = lambda x: x * x + 1    List_x = [2]    while x < n:        x = f(x)        List_x.append(x)    List_x = [x % n for x in List_x]    # calculate p = gcd(x(i) - x(j), n) and remove the same p    List_p = [gcd((List_x[i] - List_x[j]), n) for i in range(1, len(List_x)) for j in range(i)]    List_p = list(set(List_p))    List_p.sort()    # list factors of n    List_factor = [p for p in List_p if p > 1]    return  List_factorprint 'Using Pollard Pho factoring to find LCM(a, b)'print 'seed = 2, f(x) = x^2 + 1'a = int(raw_input('input a:'))b = int(raw_input('input b:'))#obtain the factors of a and b, remove one of the same factor of bothprime_a = [a / i for i in Pollard(a)] + Pollard(a)prime_b = [b / i for i in Pollard(b)] + Pollard(b)temp = list(set(prime_a + prime_b))temp.sort()prime = [i for i in temp if i != 1]#calculate LCM(a, b)LCM = a * bfor i in prime:    while (LCM / i % a == 0) and (LCM / i % b == 0):        LCM = LCM / iprint '\nLCM(a, b) = %d\n' % LCMraw_input('Press Enter to exit()')
1 0