题目:
引用
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?
这个题目解得很差,写了个函数,传入1到10,速度还行,传入1到20,竟然计算了XX秒...看来算法太烂了,自我笔试下@@@@
我的python代码:
def gcd(list):
n = max(list)
flag = True
i = 1
while True:
for j in list:
if (n * i) % j != 0:
flag = False
break
if flag:
return n * i
else:
flag = True
i += 1
print gcd(range(1,21))
看了别人的解法,选了个比较大的基数,思路差不多:
i = 9699690 # Continuation.9699690=2*3*5*7*11*13*17*19
while 1:
print "Testing: %s" % i
for x in range(1, 21):
print "%s:" % x,
if i % x != 0:
print "Fail"
break
else:
print "Pass"
else:
print "Solution: %s" % i
break
i+=9699690
一种比较好的解决方案,核心思想是利用分解质因数来求解最大公倍数:
num = 20
'''
isSolved = False
i = 0
while not isSolved:
for ii in range(2,num+1):
if i % ii == 0 and i != 0:
if ii == num: isSolved = True
else:
i = i + num
break
print 'Lowest divisor: ', i
'''
def isPrime(a):
prime=True
for i in range(2,a):
if (a % i == 0): prime=False
if prime: return True
else: return False
factorz = []
primeFactorz = []
def getPrimeFactors(a):
gotFactor = False
for ii in range(2,a+1):
if a % ii == 0:
gotFactor = True
b = a/ii
if isPrime(ii): factors.append(ii)
else: getPrimeFactors(ii)
if isPrime(b) and b != 1: factors.append(b)
else: getPrimeFactors(b)
if gotFactor: break
for i in range(2,num+1):
factors=[]
getPrimeFactors(i)
factorz.append(factors)
print 'Printing Factors of 2 through', num
for i in factorz:
print i
new=[]
total=[]
def getHighestPow(a):
counthigh = 0
for i in factorz:
count = 0
for ii in i:
if ii == a:
count = count + 1
if count > counthigh:
counthigh = count
if a not in new:
new.append(a)
total.append(a**counthigh)
for i in factorz:
for ii in i:
getHighestPow(ii)
sum=1
for i in total:
sum = sum * i
print 'Lowest Common Multiple: ', sum