projecteuler.net解题记录,参考了肥猫的(1-3题)

来源:互联网 发布:windows 10 1709 iso 编辑:程序博客网 时间:2024/06/09 20:59
一个很有意思的解题网站.
我主要用python来解决.

第一题:
Add all the natural numbers below one thousand that are multiples of 3 or 5.
求1000以下的能被3或5整除的整数之和.
  1. >>> sum([i for i in xrange(1000) if not i%3 or not i%5])
  2. 233168
第二题:
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
Fibonacci数列中小于4百万的偶数之和.
  1. # -*- coding: gb2312 -*-
  2. from __future__ import generators
  3. def fibo(n):
  4.     """定义一个Fibonacci数列生成器"""
  5.     nextItem = 0
  6.     beyondItem = 1
  7.     currentN = 0
  8.     while currentN <= n:
  9.         yield nextItem
  10.         nextItem, beyondItem = beyondItem,nextItem + beyondItem
  11.         currentN += 1
  12. # 找出数列中第一个大于4000000的序号
  13. i = 1
  14. while list(fibo(i))[-1]<4000000:
  15.     i += 1
  16. print sum( [ j for j in fibo(i) if not j%2 ] 
第三题:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

找出指定数的最大质因数

  1. # -*- coding: gb2312 -*-
  2. from __future__ import generators
  3. import math
  4. num = 600851475143
  5. def zhisu(m):
  6.     """分解质因数的生成器"""
  7.     n = m
  8.     start = 2
  9.     c_flag = 1
  10.     while c_flag:
  11.         c_flag = 0  # 本轮是否找出了一个质因数,如果否,则已经剩最后一个质因数了.
  12.         for i in xrange(start,int(math.sqrt(n)+1)):
  13.             if not n%i:
  14.                 yield i
  15.                 n = n/i
  16.                 start = i
  17.                 c_flag = 1
  18.                 break
  19.     if n<>m:
  20.         yield n
  21. print list(zhisu(num))

原创粉丝点击