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 = c
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的最大质因子。
def eula(s):
i = 2
while s != 1:
if not s%i:
s = s/i
maxPrime = i
else:
i += 1
return maxPrime
print eula(600851475143)
Answer 3: 6857
Problem 4: Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
求两个三位整数乘积中,最大的回文数。
思路:算出所有的两个三位整数的乘积,放入一个列表中,取出最大的回文数。
#!/usr/bin/env python
# 定义回文数判断函数
def palindrome(n):
lenN = len(str(n))
for i in xrange(lenN/2):
if str(n)[i] != str(n)[-1-i]:
return False
return True
myList = [i * j for i in xrange(999,99,-1) for j in xrange(999,99,-1)]
myList.sort(reverse=True) #将myList从大到小排列,方便循环找到答案后跳出程序。
for eachItem in myList:
if palindrome(eachItem):
print eachItem
break
Answer 4: 906609