problem1
http://projecteuler.net/index.php?section=problems&id=1
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.
中文翻译:
小于10并且能够被3或者5整除的自然数是3,5,6,9,它们之和是23。
计算小于1000并且能够被3或者5整除的自然数之和。
够简单!
use python2.5
problem2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
中文翻译:
每一个新的斐波那契项是它之前的两项之和。
以1和2开始,最开始的10项斐波那契项是:
1,2,3,5,8,13,21,34,55,89,……
计算一个每项都不超过4百万的斐波那契数列中的偶数之和。
use python2.5
这个解法纯属一一对应,没有考虑斐波那契数列的规律。看看官方论坛上牛人的解决办法:
---------------------------------------------------------------------------------
This may be a small improvement. The Fibonacci series is:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610...
Now, replacing an odd number with O and an even with E, we get:
O, O, E, O, O, E, O, O, E, O, O, E, O, O, E...
And so each third number is even. We don't need to calculate the odd numbers. Starting from an two odd terms x, y, the series is:
x, y, x + y, x + 2y, 2x + 3y, 3x + 5y
And in Python, my solution is:
def calcE():
x = y = 1
sum = 0
while (sum < 1000000):
sum += (x + y)
x, y = x + 2 * y, 2 * x + 3 * y
return sum
With this, you don't need to use an % to calculate if a number is even. Using a fast computer, this took less than 0.01 secs to calculate.
---------------------------------------------------------------------------------------------------
这规律都能找出来,这哥们够狠!
把这个方法提取一下:
当执行 calcE(5)的时候,正确结果应该是2,但是却为10,这个函数还有个小bug,我来修复一下: