[英]Consecutive Prime Sum
我正在解決Euler項目的第50 個問題。
問題是:
找到一百萬以下的素數,可以將其寫為最連續的素數之和。
例如41 = 2 + 3 + 5 + 7 + 11 + 13
41
是可以寫為最連續的素數之和的素數。
我編寫了一個代碼,以查找可以寫為最連續的素數之和的低於1000
素數,以檢查我的代碼是否找到可以寫為低於1000
的最連續素數之和的素數( 953
) 。 這是我想出的:
#!/usr/bin/python
import prime
p = prime.genprimes(1000)
prms = [i for i in p]
for prm in prms:
count = 0
p = prm
temp = []
for a in prms:
p -= a
temp.append(a)
count += 1
if p == 0:
print prm, '\t', count, '\t', temp
prime.py
:
#!/usr/bin/python
def genprimes(limit):
"""
Returns the prime numbers(generator) until the limit(inclusive) given.
"""
D = {}
q = 2
while q <= limit:
if q not in D:
yield q
D[q * 2] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
運行代碼時的輸出:
2 1 [2]
5 2 [2, 3]
17 4 [2, 3, 5, 7]
41 6 [2, 3, 5, 7, 11, 13] # Longest sum of consecutive primes that adds to a prime below 100
197 12 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
281 14 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
問題是它找不到素數953
,素數是連續的素數的最長和,加到1000
以下的素數。
因此,我更改了代碼以對for
循環中prm
為953
時的工作進行故障排除:
#!/usr/bin/python
import prime
p = prime.genprimes(1000)
prms = [i for i in p]
found = []
for prm in prms:
if prm == 953:
p = prm
for a in prms:
print p, '\t', a
p -= a
if p < -100:
break
輸出:
953 2
951 3
948 5
943 7
936 11
925 13
912 17
895 19
876 23
853 29
824 31
793 37
756 41
715 43
672 47
625 53
572 59
513 61
452 67
385 71
314 73
241 79
162 83
79 89
-10 97
知道我在這里做錯了嗎? 謝謝你的幫助。
您的循環始終從索引2開始。連續的素數似乎不一定要從素數2開始。您將需要改變連續加法的起始素數。
一個較小的示例:如果找到的連續質數的最大和小於10,則為3 + 5 = 8
,而不是2 + 3 = 5
。
不一定(也不是)總是通過將所有從2開始的素數相加來獲得最大的和。
在TCS CodeVita 2016中提出了這個問題
#include<iostream>
using namespace std;
int main(){
long long int num=0;
cout<<"Enter the Size to count Prime number till NUM : ";
cin>>num;
long long int ary[num],j=2;
ary[0] =2,ary[1]=3;
for(int i=2;i<=num;i++){ // loop will add the prime number till num
if(i%2 != 0 && i%3 != 0){
ary[j] = i;
j++;
}
}
long long int k,sum=0,count=0;
cout<<"Sum of Consecutive Prime numbers from "<<2<<" to "<<num<<endl;
for(int i=0;i<=j;i++){
for(k=0;k<j;k++){
sum+= ary[k];
if(sum %2 !=0 && sum%3!=0 && sum<=num){
count++;
cout<<sum<<endl;
}
}
}
cout<<"Total Consecutive Count : "<<count<<endl;
}
輸出值
樣本輸出1
Enter the Size to count Prime number till NUM : 20
Sum of Consecutive Prime numbers from 2 to 20
5
17
Total Consecutive Count : 2
樣本輸出2
Enter the Size to count Prime number till NUM : 100
Sum of Consecutive Prime numbers from 2 to 100
5
17
41
77
Total Consecutive Count : 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.