我试图在projecteuler中解决问题5.问题如下
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
我写了一个简单的python程序
primes = [2,3,5,7,11,13,17,19]
prod = 1
#function returns the list of prime factors of 'n'
def find_pf(n):
pf = []
for j in primes:
if i % j == 0:
pf.append(j)
return pf
#multiplies all the prime factors of all the numbers
#from 1[1..20]
for i in range(1,21):
lst = find_pf(i)
for i in lst:
prod *= i
#verifies that 'n' is diviible evenly by [1..20]
count = 0
def test_n(n):
global count
for i in range(1,21):
if n % i != 0:
count += 1
print ('smallest number divisible by [1..20] {}'.format(prod))
test_n(prod)
print('Total failures {}'.format(count))
上述程序获得的结果是
smallest number divisible by [1..20] 1055947052160000
Total failures 0
答案1055947052160000
不正确。?有人可以指出上述程序有什么问题吗?或者建议正确的方法来解决这个问题?
答案 0 :(得分:3)
错误在
#multiplies all the prime factors of all the numbers
#from 1[1..20]
for i in range(1,21):
lst = find_pf(i)
for i in lst:
prod *= i
你只对任何素数的最高必要力量感兴趣。 例如,您要查找的值应该可被16整除。您的代码会查找可被2 * 4 * 8 * 16整除的数字。
答案 1 :(得分:2)
您的代码正在寻找太多素数。寻找最大的就足够了:例如如果数字可以被16分割,则它已经可以被8分割。
primes = [2,3,5,7,11,13,17,19]
prod = 1
for p in primes:
n = 2
prod *= p
while (p**n < 21):
prod *= p
n += 1
print prod
你来了
232792560
答案 2 :(得分:1)
def lcm(*values):
values = [value for value in values]
if values:
n = max(values)
m = n
values.remove(n)
while any(n % value for value in values):
n += m
return n
return 0
reduce(lcm, range(1, 20))
In [3]: reduce(lcm, range(1, 20))
Out[3]: 232792560
reduce将“两个参数的函数累加到从左到右的可迭代项中,以便将迭代减少到单个值。”
def add_nums(a,b):
print a,b # added print to show values
return a+b
reduce(add_nums, [1, 2, 3, 4, 5]) #calculates ((((1+2)+3)+4)+5)