用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.
784 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的最大质因子。
740 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. 水仙花数是从左向右和从右向左读都相同的自然数。
926 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.
696 0
|
8天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
8天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
12天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
29天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
159 0
|
1天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
10 1
|
1天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
18 0

热门文章

最新文章