Problem 50 Consecutive prime sum (线性筛)

深藏阁楼爱情的钟 2022-07-15 03:22 271阅读 0赞

Consecutive prime sum

Problem 50

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?




















Answer:
997651
Completed on Mon, 31 Oct 2016, 10:49

代码:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> primes;
  4. int prime[1000000];
  5. void init()
  6. {
  7. for(int i = 0 ; i < 1000000 ; i++){
  8. prime[i] = 1;
  9. }
  10. for(int i = 2 ; i < 1000000; i++)
  11. {
  12. if (prime[i])
  13. {
  14. primes.push_back(i);
  15. if(i <= (int)sqrt((double)1000000))
  16. {
  17. for(int t = i*i ; t<1000000 ; t+=i)//prime[i*i+k*i]=false
  18. {
  19. prime[t] = 0;
  20. }
  21. }
  22. }
  23. }
  24. }
  25. int main()
  26. {
  27. init();
  28. int max = 0;
  29. int maxlen = 0, maxsum = 0, cursum = 0;
  30. for(int i = 2 ; i < primes.size() ; i++)
  31. {
  32. cursum = 0;
  33. for(int j = i ; j < primes.size() ; j++)
  34. {
  35. cursum+=primes[j];
  36. if (cursum>=1000000) break;
  37. if (prime[cursum] && j - i > maxlen )
  38. {
  39. maxlen = j-i;
  40. maxsum = cursum;
  41. }
  42. }
  43. }
  44. cout<<maxsum<<endl;;
  45. return 0;
  46. }

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读