当前位置: 首页 > news >正文

欧拉计划的Python解法(1-10)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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 < 4000000:
    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 < 4000000:
    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,若能被整除,则取结果继续除以2,若不能则除以3,依序递增,直到被自己除,此时的数字即为所求的最大质因子。

def eula(s):
    i = 2
    while s != 1:
        if not s % i:
            s = s / i
            maxPrime = i
        else:
            i += 1
    return maxPrime

print eula(600851475143)

Answer 3: 6857

Problem 4. Largest palindrome product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 &times; 99.

Find the largest palindrome made from the product of two 3-digit numbers.

求两个三位整数乘积中,最大的回文数。

思路:算出所有的两个三位整数的乘积,放入一个列表中,取出最大的回文数。

#!/usr/bin/env python

# 定义回文数判断函数
def palindrome(n):
    lenN = len(str(n))
    for i in xrange(lenN/2):
        if str(n)[i] != str(n)[-1-i]:
            return False
    return True

myList = [i * j for i in xrange(999,99,-1) for j in xrange(999,99,-1)]
myList.sort(reverse=True)    #将myList从大到小排列,方便循环找到答案后跳出程序。

for eachItem in myList:
    if palindrome(eachItem):
        print eachItem
        break

Answer 4: 906609

Problem 5. Smallest multiple

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

求能被1~20的每个数都整除的最小值。

这道题,一开始我想用循环做,后来发现我错了,由于答案太大(9位数),等解释器转了半天都没结果,遂放弃。

思路:如果一个数n能被20以内的整数整除,应当满足以下条件:

假设一个质数i,并且i的j次方不大于20,则这个数应当能被i的j次方整除,即:n % (i ** j) == 0

这样,不用编程的方法可以求得:n = (2 ** 4) * (3 ** 2) * 5 * 7 * 11 * 13 * 17 * 19

#!/usr/bin/env python

from math import sqrt

#将不大于20的所有质数放入列表myPrime中
myPrime = [n for n in xrange(2,21) if 0 not in [n % i for i in xrange(2,int(sqrt(n))+1)]]

#循环求得每一个质数的次方值j,并将结果加乘到result中去
result = 1
for i in myPrime:
    j = 1
    while i ** j <= 20:
        j += 1
    result = result * i ** (j - 1)

print result

Answer 5: 232792560

Problem 6. Sum square difference

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

求“100的和的平方”与“100的平方和”的差。

递归:

#!/usr/bin/env python

def sum(n):
    if n == 0:
        sumN = 0
    else:
        sumN = sum(n-1) + n
    return sumN

def square(n):
    if n == 0:
        squareN = 0
    else:
        squareN = square(n-1) + n ** 2
    return squareN

print sum(100) ** 2 - square(100)

Answer 6: 25164150

Problem 7. 10001st prime

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

求第10001个质数。

思路:使用while循环,验证从2开始的每一个正整数是否为质数,若是,则给计数器+1,直到计数器值为10001。

#/usr/bin/env python

from math import sqrt

#质数验证函数
def isPrime(n):
    for i in xrange(2,int(sqrt(n))+1):
        if n % i == 0:
            return False
    return True

i = 1
counter = 0    #计数器初始值为0
while counter < 10001:    #计数器到10001时跳出循环
    i += 1
    if isPrime(i):
        counter += 1
print i

Answer 7: 104743

Problem 8. Largest product in a series

Find the greatest product of five consecutive digits in the 1000-digit number.


73167176531330624919225119674426574742355349194934

96983520312774506326239578318016984801869478851843

85861560789112949495459501737958331952853208805511

12540698747158523863050715693290963295227443043557

66896648950445244523161731856403098711121722383113

62229893423380308135336276614282806444486645238749

30358907296290491560440772390713810515859307960866

70172427121883998797908792274921901699720888093776

65727333001053367881220235421809751254540594752243

52584907711670556013604839586446706324415722155397

53697817977846174064955149290862569321978468622482

83972241375657056057490261407972968652414535100474

82166370484403199890008895243450658541227588666881

16427171479924442928230863465674813919123162824586

17866458359124566529476545682848912883142607690042

24219022671055626321111109370544217506941658960408

07198403850962455444362981230987879927244284909188

84580156166097919133875499200524063689912560717606

05886116467109405077541002256983155200055935729725

71636269561882670428252483600823257530420752963450

找出这个1000位的整数中连续5个数字的最大乘积。

思路:使用字符串切片符获得连续的5个数字,将所有结果列入一个列表中,取最大值。

#!/usr/bin/env python

str1000 = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'

multilist = [int(str1000[i]) * int(str1000[i+1]) * int(str1000[i+2]) * int(str1000[i+3]) * int(str1000[i+4]) for i in xrange(len(str1000)-4)]

print max(multilist)

Answer 8: 40824

Problem 9. Special Pythagorean triplet

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.

Find the product abc.

找到满足a+b+c=1000的毕达哥拉斯三元组,并求三元组的乘积。

思路:由于a < b < c,因此a不会大于333,b不会大于500,因此考虑用for循环。

#!/usr/bin/env python

for a in xrange(1, 334):
    for b in xrange(a, 501):  #由于b大于a,因此这里设计循环最小值等于a
        c = 1000 - a - b
        if c ** 2 == a ** 2 + b ** 2:
            print a, b, c, a * b * c

Answer 9: 31875000

Problem 10. Summation of primes

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

求2000000以下的素数和。

#/usr/bin/env python

from math import sqrt

def isPrime(n):
    for i in xrange(2,int(sqrt(n))+1):
        if n % i == 0:
            return False
    return True

summa = 0
for i in xrange(2,2000000):
    if isPrime(i):
        summa += i

print summa

Answer 10: 142913828922

转载于:https://my.oschina.net/plutonji/blog/207894

相关文章:

  • SharePoint 网站登录不上,3次输入用户名/密码白页、
  • 关于C语言指针几个容易混淆的概念
  • 八一八android开发规范(一种建议)
  • 产品经理:想爱没那么简单
  • 进程ps、kill 、grep
  • 准确修改虚拟机名称方法
  • cacti导入Linux主机模板 Windows主机模板
  • 英文字体免费下载:10款最新的高品质字体
  • sass教程汇总
  • Mark Russinovich 的博客:Windows Azure 主机更新:原因、时间和方式
  • 分享几个响应式开发的代码小技巧
  • adb 使用体验
  • 绝美风景!20幅全球地理风光摄影欣赏【组图】
  • volatile synchronized AtomicInteger的区别
  • JSP/Servlet 获取真实IP地址
  • [分享]iOS开发 - 实现UITableView Plain SectionView和table不停留一起滑动
  • 【附node操作实例】redis简明入门系列—字符串类型
  • C++入门教程(10):for 语句
  • IDEA 插件开发入门教程
  • Java 23种设计模式 之单例模式 7种实现方式
  • java 多线程基础, 我觉得还是有必要看看的
  • Java 最常见的 200+ 面试题:面试必备
  • JavaScript 基本功--面试宝典
  • java概述
  • Terraform入门 - 1. 安装Terraform
  • 后端_ThinkPHP5
  • 前端自动化解决方案
  • 如何使用 OAuth 2.0 将 LinkedIn 集成入 iOS 应用
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 数据可视化之 Sankey 桑基图的实现
  • 算法---两个栈实现一个队列
  • 学习HTTP相关知识笔记
  • 原生JS动态加载JS、CSS文件及代码脚本
  • - 转 Ext2.0 form使用实例
  • 大数据全解:定义、价值及挑战
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • ## 临床数据 两两比较 加显著性boxplot加显著性
  • (bean配置类的注解开发)学习Spring的第十三天
  • (Python) SOAP Web Service (HTTP POST)
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (生成器)yield与(迭代器)generator
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)shell中括号的特殊用法 linux if多条件判断
  • (转)总结使用Unity 3D优化游戏运行性能的经验
  • .htaccess配置常用技巧
  • .NET : 在VS2008中计算代码度量值
  • .NET CORE 第一节 创建基本的 asp.net core
  • .NET 的静态构造函数是否线程安全?答案是肯定的!
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地中转一个自定义的弱事件(可让任意 CLR 事件成为弱事件)
  • .net经典笔试题
  • .Net语言中的StringBuilder:入门到精通
  • .NET值类型变量“活”在哪?
  • @data注解_一枚 架构师 也不会用的Lombok注解,相见恨晚