欧拉计划题目中的一些非常精致的解法
problem 47
The first two consecutive numbers to have two distinct prime factors are:
14 = 2
7
15 = 3
5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2²
7
23
645 = 3
5
43
646 = 2
17
19.
Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers?
这里有一个非常精致的解(在论坛上看到的)
lim = 1000000 l = 4 sieve = [0] * lim ls = [l] * l for i in range(2,int(math.sqrt(lim)) + 1): if sieve[i] == 0: sieve[i+i::i] = [x + 1 for x in sieve[i+i::i]] for i in range(2,len(sieve) - l): if sieve[i:i+l] == ls: print i break
该解法将2到1000000中的每个数,统计其所含有的素数因子的个数,若有连续4个数含有4个素数因子,既符合题目条件。该方法也可以用于获得素数列表,如下所示
def primes(limit): a = [True] * limit a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: yield i for n in range(i*i, limit, i): a[n] = False

浙公网安备 33010602011771号