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

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

Pollard rho算法基本思路

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

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] 输出LCM yes no

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

具体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 power
def 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_factor


print '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 both
prime_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 * b
for i in prime:
    while (LCM / i % a == 0) and (LCM / i % b == 0):
        LCM = LCM / i
print '\nLCM(a, b) = %d\n' % LCM
raw_input('Press Enter to exit()')
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值