Blame | Last modification | View Log | Download | RSS feed
def PollardPM1(N,B):'''Implementation of the Pollard p-1 algorithm for factoring primes'''a = 2;for i in range(2,B):a = a**i % Nd = GCD(a-1,N)if 1 < d < N:return delse:return -1;def PollardRho(N,x_1):'''Implementation of the Pollard Rho algorithm for factoring primes'''x = x_1y = PollardRhoHelper(x) % Ng = GCD(abs(x-y),N)iterations = 0;while g == 1:iterations += 1x = PollardRhoHelper(x) % Ny = PollardRhoHelper(y) % Ny = PollardRhoHelper(y) % Ng = GCD(abs(x-y),N)print("Iterations: %d\n" % (iterations))if g == N:return -1else:return gdef PollardRhoHelper(x):return x**2 + 1def Extended_Euclidian(a, b):''' Takes values a and b and returns a tuple (r,s,t) in the following format:r = s * a + t * b where r is the GCD and s and t are the inverses of a and b'''t_ = 0t = 1s_ = 1s = 0q = int(a/b)r = a - q * b# print("%d\t= %d * %d + %d" % (a, q, b, r))while r > 0:temp = t_ - q * tt_ = tt = temptemp = s_ - q * ss_ = ss = tempa = bb = rq = int(a/b)r = a - q * b# print("%d\t= %d * %d + %d" % (a, q, b, r))r = breturn (r, s, t)def GCD(q,N):'''Returns the multiplicative inverse of a and b'''ret = Extended_Euclidian(q,N)return ret[0]def Inverse(a, b):'''Returns the multiplicative inverse of a mod b'''ret = Extended_Euclidian(a,b)if (ret[1] < 0):inv = ret[1] + belse:inv = ret[1]return invif __name__ == '__main__':prime1 = 112426043prime2 = 262063prime3 = 9420457for i in range(100):p = PollardPM1(prime1,i)if p != -1:print("Prime found with B = %d with value %d\n" % (i,p))breakp = PollardRho(prime2,1)print("A prime factor of %d is %d\n" % (prime2,p))p = PollardRho(prime3,1)print("A prime factor of %d is %d\n" % (prime3,p))