Problem 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?

问题5:

  2520是最小的能被1到10的所有的数整除的整数。
  求最小的能被1到20的所有的数整除的整数。

方法一:

  本题为求1到n的最小公倍数
  求多个数的最小公倍数,可以先求两个数的最小公倍数,再求所得到的值和剩下的数的最小公倍数。
  求两个数的最小公倍数,可以用两个数的乘积除以两个数的最大公约数
  求两个数的最大公约数,可以用辗转相除法

方法一
def GCD(x,y):
if x>y:
return fi(y,x)
if x==0:
return y
return GCD(y%x,x)
def LCM(x,y):
return (x*y)//GCD(x,y)
def f(x):
a
=1
for i in range(2,x+1):
a
=LCM(a,i)
return a

方法二:

  求最小公倍数,还以将所有的数进行质因数分解,然后找到所有质因子的最大次幂,将他们相乘可以得到最小公倍数。
  本题为求1到n的最小公倍数,因此不必将所有的数分解因子。
  因为整数不可能有比他大的因子,所以所有质因子为1到20 的素数。
  因为pk+1>n所以任何有pk+1为因子的数必大于n,又因为pk<n,所以pk是1到n中的一个整数。 
  所以对于素数p,假设 pk<=n<pk+1则k为1到n的数进行质因数分解后p的最大次幂 。

方法二
from eulertools import primes
from math import log
from functools import reduce
def f2(n):
return reduce(lambda x,y:x*y,(i**int(log(n,i)) for i in primes(n)))

  可以使用筛法求素数

primes
def primes(n):
if n<2:
raise StopIteration
else:
yield 2
l
=[True for i in range((n-1)//2)]
for i in range(len(l)):
if l[i]:
yield 2*i+3
for j in range(3*i+3,len(l),2*i+3):
l[j]
=False
posted on 2011-05-04 12:33  class  阅读(1156)  评论(2编辑  收藏  举报