有個很有意思的網站 ProjectEuler.net ,提出了200多道數學問題,要求讀者用計算機求解,不限制所用的計算機語言。
(2008年11月)試着用Python做了幾道,挺有意思的。
- Add all the natural numbers below one thousand that are multiples of 3 or 5.
- Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
- Find the largest prime factor of a composite number.
- Find the largest palindrome made from the product of two 3-digit numbers.
- What is the smallest number divisible by each of the numbers 1 to 20?
E001
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
求1000以下,所有是3或5倍數的數之和。
def problem1():
a, b, c = 3, 5, 999
f = lambda x,lmt=c: x*(lmt/x)*(lmt/x+1)/2
return f(a)+f(b)-f(a*b)
if __name__=='__main__':
print str(problem1())
關鍵是 1000以内能被3整除的數之和是 3(1+2+3+...+333)