歐拉計劃 47

最小的兩個具有兩個不同質數因子的連續整數是:

14 = 2 × 7
15 = 3 × 5

最小的三個具有三個不同質數因子的連續整數是:

644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.

找出最小的四個具有四個不同質數因子的整數。它們之中的第一個是多少?

import math
import time


def is_prime(x):
    """ 質數判斷 """
    if x == 1:
        return False
    if x == 2:
        return True
    assert math.floor(x) == x and x > 0
    x_sqrt = int(math.sqrt(x))
    l = [2]
    l.extend(range(3, x_sqrt + 1, 2))
    for i in l:
        if x % i == 0:
            return False
    return True


def get_factor(x):
    """ 質數因子 """
    factor = []
    if is_prime(x):
        factor.extend([x])
        return factor
    xx_sqrt = int(math.sqrt(x))
    for i in range(2, xx_sqrt + 1):
        if x % i == 0:
            if i in factor_dict:
                factor.extend(factor_dict[i])
            else:
                factor_ = get_factor(i)
                factor.extend(factor_)
                factor_dict[i] = factor_
            j = x // i
            if j in factor_dict:
                factor.extend(factor_dict[j])
            else:
                factor_ = get_factor(j)
                factor.extend(factor_)
                factor_dict[j] = factor_
            break
    return factor


t0 = time.time()
n = 4
consecutive_num = 2 * 3 * 5 * 7
n_factors = 0
factor_dict = dict()
while 1:
    if len(set(get_factor(consecutive_num))) == n:
        n_factors += 1
        if n_factors == n:
            break
    else:
        n_factors = 0
    consecutive_num += 1
print(consecutive_num - 3)
t1 = time.time()
print(t1 - t0)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章