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

来源:互联网 发布:ubuntu 16.04 拼音 编辑:程序博客网 时间:2024/06/10 06:41
第四题:
Find the largest palindrome made from the product of two 3-digit numbers.
找出能够分解为两个三位数相乘的最大荷花数
  1. # -*- coding: gb2312 -*-
  2. def palind(n):
  3.     """判断一个数是否荷花数"""
  4.     str_num = list(str(n))
  5.     str_num.reverse()
  6.     return n == int(''.join(str_num))
  7. s = [ i*j for i in xrange(99,999) for j in xrange(i,999) if palind(i*j) ]
  8. print s
  9. print max(s)
第五题:
What is the smallest number divisible by each of the numbers 1 to 20?
找出1-20的最小公倍数

  1. # -*- coding: gb2312 -*-
  2. # 求1-n的最小公倍数
  3. # 求两个数的最小公倍数的算法:先算出n,m的最大公约数k,然后得出:n*m/k
  4. # 最大公约数的算法:辗转相除法
  5. def gcd(n,m):
  6.     return n%m and gcd(m,n%m) or m
  7. def lcm(n,m):
  8.     return n*m/gcd(n,m)
  9. print reduce(lcm,xrange(2,21)
第六题:
What is the difference between the sum of the squares and the square of the sums?
找出前一百个自然数的平方和与和平方的差值
这个用python就比较简单了:

  1. >>> sum( [ i**2 for i in xrange(1,101) ] ) - sum(xrange(1,101))**2
  2. -25164150