Python Euler 5:可以被1到20之间的数除的最小数
我试图在projecteuler中解决问题5。问题如下Python Euler 5:可以被1到20之间的数除的最小数,python,Python,我试图在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? 我已经编写了一个简单的pyth
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
不正确。?有人能指出上面的程序有什么问题吗?或者建议解决此问题的正确方法?错误在
#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整除的数字。错误在
#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
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
你只对任何质数的最高必要幂感兴趣。
例如,您要查找的值应可被16整除。您的代码查找可被2*4*8*16整除的数字
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
将“两个参数的函数”从左到右累加到iterable的项,以便将iterable减少为单个值
将“两个参数的函数”从左到右累加到iterable的项,以便将iterable减少为单个值
您的代码正在查找太多的素数。查找最大值就足够了:例如,如果数字可以除以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
primes=[2,3,5,7,11,13,17,19]
prod=1
对于素数中的p:
n=2
产品*=p
而(p**n<21):
产品*=p
n+=1
印刷品
给你
232792560
您的代码正在查找太多的素数。查找最大值就足够了:例如,如果数字可以除以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
primes=[2,3,5,7,11,13,17,19]
prod=1
对于素数中的p:
n=2
产品*=p
而(p**n<21):
产品*=p
n+=1
印刷品
给你
232792560
参见例如,参见例如,什么是reduce()函数?它做什么?什么是reduce()函数?它有什么作用?