码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler:Problem 50 Consecutive prime sum

时间:2015-06-07 17:35:13      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:c++   project euler   

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?



#include <iostream>
#include <vector>
using namespace std;

int a[1000000];
int asize = 0;
bool isPrime[1000000] = { false };

bool prim(int n)
{
	int i;
	for (i = 2; i * i <= n; i++) 
	{
		if (n % i == 0) 
			return false;
	}
	return true;
}

void init()
{
	int i, j;
	i = 3;
	j = 1;
	a[0] = 2;
	while (1) 
	{
		if (prim(i)) 
		{
			isPrime[i] = true;
			a[j++] = i;
			if (i >= 1000000)
			{
				asize = j;
				break;
			}
		}
		i += 2;
	}
}



int main()
{
	init();
	int maxn;
	int maxlen = 0;
	for (int n = 1000; n < 1000000; n++)
	{
		
		if (isPrime[n])
		{
			for (int i = 0; i < asize; i++)
			{
				int len = 0;
				int sum = 0;
				if (a[i]>n)
					break;
				for (int j = i;; j++)
				{
					sum += a[j];
					len++;
					if (sum > n)
						break;
					if (sum == n)
					{
						if (len > maxlen)
						{
							maxlen = len;
							maxn = n;
						}
					}
				}
			}
		}
	}
	cout << maxn << " " << maxlen << endl;
	system("pause");
	return 0;
}


Project Euler:Problem 50 Consecutive prime sum

标签:c++   project euler   

原文地址:http://blog.csdn.net/youb11/article/details/46400513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!