簡體   English   中英

素數分解一個 3000 位數字,最大素數 <=104743(6 位) - 這可以在幾分鍾內在“普通”計算機上完成嗎?

[英]Prime factorize a 3000 digit number, with max prime <=104743 (6 digit) - is this possible to do on a “normal” computer in a few minutes?

我有一個 3000 位長的數字必須考慮到它的素數中。 我知道沒有大於 104743 的素因數。

由於最高因素相對較低,這是否可能在幾分鍾內在“普通”計算機上完成?

作為參考,我嘗試了我在這里找到的代碼。

def factorize(n): 
    count = 0; 

    while ((n % 2 > 0) == False):  

        # equivalent to n = n / 2; 
        n >>= 1;  
        count += 1; 

    # if 2 divides it 
    if (count > 0): 
        print(2, count); 

    # check for all the possible 
    # numbers that can divide it 
    for i in range(3, int(math.sqrt(n)) + 1): 
        count = 0; 
        while (n % i == 0):  
            count += 1; 
            n = int(n / i); 
        if (count > 0): 
            print(i, count); 
        i += 2; 

    # if n at the end is a prime number. 
    if (n > 2): 
        print(n, 1); 

n = 5*7*11*13*17*19*23*29*31*37*41*43*47;
factorize(n); 

# This code is contributed by mits 

此代碼使用 59 秒來制造一個 18 位數字,其中 47 是最高因子(102481630431415235 是“測試數字”)。 如果我停在第 47 個因素,它只使用 31 秒,但它仍然太長了,因為測試數遠遠低於我的需要。

由於您的素數相對較小,我認為如果您可以先生成素數列表並將它們用於分解,它會更快。

這是一個示例代碼:

import math

# Copied from https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188
def primes2(n):
    """ Input n>=6, Returns a list of primes, 2 <= p < n """
    n, correction = n-n%6+6, 2-(n%6>1)
    sieve = [True] * (n//3)
    for i in range(1,int(n**0.5)//3+1):
      if sieve[i]:
        k=3*i+1|1
        sieve[      k*k//3      ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
        sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
    return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]

def factorize2(n, primes):
    factors = {}
    cur_num = n
    for p in primes:
        if p*p > cur_num:
            break
        while cur_num % p == 0:
            cur_num //= p
            factors[p] = factors.get(p, 0) + 1

    if cur_num >= 2:
        factors[cur_num] = factors.get(cur_num, 0) + 1
    return factors

# Precompute the primes
primes = primes2(110000)
n = 5*7*11*13*17*19*23*29*31*37*41*43*47

result = factorize2(n, primes)
print(result)

對於示例中的數字,此代碼運行大約 50 毫秒(比您問題中的代碼快得多)。


更新:

我用以下代碼嘗試了 3000 位數字:

def generate_big_num(primes, th):
    import random
    num = 1
    while num < th:
        num *= random.choice(primes)
    return num

th = 10**3000
big_num = generate_big_num(primes, th)
print(big_num)
result = factorize2(big_num, primes)
print(result)

在我的筆記本電腦上只花了大約 60 毫秒。 所以你的問題的答案是肯定的!

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM