Problem 1. Multiples of 3 and 5
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整除的数字之和。
#!/usr/bin/env python
sum = 0
for i in xrange(1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
print sum
Answer 1: 233168
Problem 2. Even Fibonacci numbers
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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
求不大于4000000的斐波那契数列中,所有偶数之和。
两个解法:
1. 创建多个变量,变量循环迭代。效率较高。
#!/usr/bin/env python
a = 1
b = 2
fib = 3
sum = 2 #这个初始值是关键,由于下面的while循环中,斐波那契值从3开始,因此sum的初始值应为2
while fib
fib = a + b
if not fib % 2:
sum += fib
a = b
b = fib
print sum
2. 使用递归函数,递归效率较低,对于练习递归函数还是挺有帮助的。
#!/usr/bin/env python
def feb(i):
if i == 0 or i == 1:
return 1
else:
result = feb(i-1) + feb(i-2)
return result
sum = 0
i = 0
tmp = 0
while tmp
i += 1
tmp = feb(i)
if not tmp % 2:
sum += tmp
print sum
Answer 2: 4613732
Problem 3. Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
求数字600851475143的最大质因子。
思路:将此数字除以2&