Fast prime factorization module

前端 未结 7 1976
萌比男神i
萌比男神i 2020-11-29 15:44

I am looking for an implementation or clear algorithm for getting the prime factorization of N in either python, pseudocode or any

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 16:33

    You could factorize up to a limit then use brent to get higher factors

    from fractions import gcd
    from random import randint
    
    def brent(N):
       if N%2==0: return 2
       y,c,m = randint(1, N-1),randint(1, N-1),randint(1, N-1)
       g,r,q = 1,1,1
       while g==1:             
           x = y
           for i in range(r):
              y = ((y*y)%N+c)%N
           k = 0
           while (k1:  break
       return g
    
    def factorize(n1):
        if n1==0: return []
        if n1==1: return [1]
        n=n1
        b=[]
        p=0
        mx=1000000
        while n % 2 ==0 : b.append(2);n//=2
        while n % 3 ==0 : b.append(3);n//=3
        i=5
        inc=2
        while i <=mx:
           while n % i ==0 : b.append(i); n//=i
           i+=inc
           inc=6-inc
        while n>mx:
          p1=n
          while p1!=p:
              p=p1
              p1=brent(p)
          b.append(p1);n//=p1 
        if n!=1:b.append(n)   
        return sorted(b)
    
    from functools import reduce
    #n= 2**1427 * 31 #
    n= 67898771  * 492574361 * 10000223 *305175781* 722222227*880949 *908909
    li=factorize(n)
    print (li)
    print (n - reduce(lambda x,y :x*y ,li))
    

提交回复
热议问题