等差素数数列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了等差素数数列相关的知识,希望对你有一定的参考价值。
程序地址:http://www.cheemoedu.com/exercise/27
问题描述:
类似7、37、67、97、107、137、167、197,这样由素数组成的数列叫做等差素数数列。素数数列具有项数的限制,一般指素数数列的项数有多少个连续项,最多可以存在多少个连续项。
编程找出100以内的等差素数数列。
示例代码:
解题步骤: #1. 筛法找到100所有素数 #2. 对于素数list内素有俩两组合,构造等差数列a0, a1项 #3. 计算出a2, 查表判断a2是否是素数,是素数则能构成素数等差序列, 计算a3... def findAllPrime(n): pt = [True] * n prime = [] for p in range(2, n): if not pt[p]: continue prime.append(p) for i in range(p * p, n, p): pt[i] = False return prime, pt prime, pt = findAllPrime(100) print prime for i in range(len(prime)): for j in range(i + 1, len(prime)): a0, a1 = prime[i], prime[j] an = a1 + a1 - a0 s = [] while an < 100 and pt[an]: s.append(an) an += a1 - a0 if s: print [a0, a1] + s
结果:
[3, 5, 7] [3, 7, 11] [3, 11, 19] [3, 13, 23] [3, 17, 31] [3, 23, 43] [3, 31, 59] [3, 37, 71] [3, 41, 79] [3, 43, 83] [5, 11, 17, 23, 29] [5, 17, 29, 41, 53] [5, 23, 41, 59] [5, 29, 53] [5, 47, 89] [7, 13, 19] [7, 19, 31, 43] [7, 37, 67, 97] [7, 43, 79] [11, 17, 23, 29] [11, 29, 47] [11, 41, 71] [11, 47, 83] [13, 37, 61] [13, 43, 73] [17, 23, 29] [17, 29, 41, 53] [17, 53, 89] [19, 31, 43] [19, 43, 67] [23, 41, 59] [23, 47, 71] [23, 53, 83] [29, 41, 53] [29, 59, 89] [31, 37, 43] [37, 67, 97] [41, 47, 53, 59] [43, 61, 79, 97] [47, 53, 59] [47, 59, 71, 83] [53, 71, 89] [59, 71, 83] [61, 67, 73, 79] [61, 79, 97] [67, 73, 79]
代码分析:
根据它的解题步骤来说,先是求出100以内的所有素数放到列表prime中,然后对列表中素数两两组合构造成等差数列的a0和a1项(实现方法就是用两个for循环,第一个循环从列表开始到结束,第二个循环从第一个开始位置加一道结束),现在已经知道了等差数列的两项,那么公差就是二者之差,第三项就是第二项加公差,然后判断第三项是否小于100且为素数,是的话就是等差素数,并且在根据该值加公差得到下一个数,依次判断即可
详细流程:
官方提供了该题的解题视频:http://www.iqiyi.com/w_19rt5h3qx5.html#vfrm=8-8-0-1
我的代码:
之前打算用an=a1+(n-1)*d的方式来做的,但是发现有问题,后来借鉴了示例代码的解题思路,写出来了,但是发现和示例代码没什么两样,也贴出来吧。
import math def prime(m): count=0 for i in range(2,int(math.sqrt(m))+1): if m%i==0: count=1 if count==1: return False else: return True x=[] for j in range(2,100): if prime(j): x.append(j) for k in range(len(x)): for l in range(k+1,len(x)): d=x[l]-x[k] res=[] an=x[l]+d while an<100 and an in x: res.append(an) an=an+d if res: print [x[k],x[l]]+res,
结果:
[3, 5, 7] [3, 7, 11] [3, 11, 19] [3, 13, 23] [3, 17, 31] [3, 23, 43] [3, 31, 59] [3, 37, 71] [3, 41, 79] [3, 43, 83] [5, 11, 17, 23, 29] [5, 17, 29, 41, 53] [5, 23, 41, 59] [5, 29, 53] [5, 47, 89] [7, 13, 19] [7, 19, 31, 43] [7, 37, 67, 97] [7, 43, 79] [11, 17, 23, 29] [11, 29, 47] [11, 41, 71] [11, 47, 83] [13, 37, 61] [13, 43, 73] [17, 23, 29] [17, 29, 41, 53] [17, 53, 89] [19, 31, 43] [19, 43, 67] [23, 41, 59] [23, 47, 71] [23, 53, 83] [29, 41, 53] [29, 59, 89] [31, 37, 43] [37, 67, 97] [41, 47, 53, 59] [43, 61, 79, 97] [47, 53, 59] [47, 59, 71, 83] [53, 71, 89] [59, 71, 83] [61, 67, 73, 79] [61, 79, 97] [67, 73, 79]
以上是关于等差素数数列的主要内容,如果未能解决你的问题,请参考以下文章