python in range函数 (1、10、-1)_欧拉计划的Python解法(1-10)

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&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值