本题来自 Project Euler 第8题:https://projecteuler.net/problem=8
# Project Euler: Problem 8: Largest product in a series # The four adjacent digits in the 1000-digit number # that have the greatest product are 9 × 9 × 8 × 9 = 5832. # Find the thirteen adjacent digits in the 1000-digit number # that have the greatest product. What is the value of this product? # Answer: 23514624000 n1 = '73167176531330624919225119674426574742355349194934' n2 = '96983520312774506326239578318016984801869478851843' n3 = '85861560789112949495459501737958331952853208805511' n4 = '12540698747158523863050715693290963295227443043557' n5 = '66896648950445244523161731856403098711121722383113' n6 = '62229893423380308135336276614282806444486645238749' n7 = '30358907296290491560440772390713810515859307960866' n8 = '70172427121883998797908792274921901699720888093776' n9 = '65727333001053367881220235421809751254540594752243' n10 = '52584907711670556013604839586446706324415722155397' n11 = '53697817977846174064955149290862569321978468622482' n12 = '83972241375657056057490261407972968652414535100474' n13 = '82166370484403199890008895243450658541227588666881' n14 = '16427171479924442928230863465674813919123162824586' n15 = '17866458359124566529476545682848912883142607690042' n16 = '24219022671055626321111109370544217506941658960408' n17 = '07198403850962455444362981230987879927244284909188' n18 = '84580156166097919133875499200524063689912560717606' n19 = '05886116467109405077541002256983155200055935729725' n20 = '71636269561882670428252483600823257530420752963450' n = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10 + n11 + n12 + n13 + n14 + n15 + n16 + n17 + n18 + n19 + n20 lst = [] #用来存放13位数字之积的列表 p = 1 #初始化每个13位数字之积 for i in range(1000-12): for j in range(13): p = p * int(n[i+j]) lst.append(p) p = 1 #计算完每一组‘13位数字之积’之后,重置p为1 print(max(lst))
有一个 1000 位的数字,任意选取相邻的 13 个数字相乘,求其中最大的乘积。
老实说,要找出这个最大的乘积并不难,遍历一下就好。但——1000位的数字?放在 PyCharm 里根本就一眼望不到尾好吗?只好按网页显示的那样断成 20 行字符串,分别赋值,然后再连接起来用。之后就简单了,从第 1 个数字开始,每次选取 13 个数字相乘,乘积放在 lst 列表里,最后把 max(lst) 给 print 出来就行了。