用Python解答 ProjectEuler问题(2)

简介: E002 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, .
E002
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.

找出不大于4,000,000的斐波那契数列中偶数值的总和。


def problem2():
    a, b, c = 1, 2, 4*10**6
   
    #掐头
    if 0==a%2:
        sum = 2*a
    elif 0==b%2:
        sum = 2*b
    else:
        sum = 0
       
    while b<=c:
        a, b = b, a+b
        sum += b
   
    #去尾
    if 0!=b%2:
        sum -= b
        if 0!=a%2:
            sum -= a
           
    return sum/2

if __name__=='__main__':
    print str(problem2())
目录
相关文章
|
Python
用Python解答 ProjectEuler问题(1)
有个很有意思的网站 ProjectEuler.net ,提出了200多道数学问题,要求读者用计算机求解,不限制所用的计算机语言。 (2008年11月)试着用Python做了几道,挺有意思的。 Add all the natural numbers below one thousand that are multiples of 3 or 5.
875 0
|
Python
用Python解答 ProjectEuler问题(3)
E003 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? 求600851475143的最大质因子。
807 0
|
Python
用Python解答 ProjectEuler问题(4)
E004 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. 水仙花数是从左向右和从右向左读都相同的自然数。
1002 0
|
Python
用Python解答 ProjectEuler问题(5)
E005 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
762 0
|
2月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
274 102
|
2月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
299 104
|
2月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
251 103
|
2月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
191 82
|
1月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
171 3
|
1月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
390 3

推荐镜像

更多
下一篇
oss云网关配置