您的位置:首页 > 编程语言 > Go语言

Project Euler:Problem 46 Goldbach's other conjecture

2015-06-07 10:04 423 查看
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.

9 = 7 + 2×12

15 = 7 + 2×22

21 = 3 + 2×32

25 = 7 + 2×32

27 = 19 + 2×22

33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?

#include <iostream>
using namespace std;

bool isPrime[1000010];

bool gold(int n)
{
	for (int i = 2; i < n; i++)
	{
		if (isPrime[i] == true)
		{
			
			int tmp = n - i;
			//cout << i << " " << tmp << endl;
			if (tmp % 2 == 0)
			{
				int k = sqrt(tmp / 2);
				if (k*k == tmp / 2)
					return true;
			}
		}
	}
	return false;
}

int main()
{
	memset(isPrime, true, sizeof(isPrime));
	for (int i = 2; i <= 1010; i++)
	{
		if (isPrime[i])
		{
			for (int j = 2; j*i < 1000010; j++)
			{
				isPrime[i*j] = false;
			}
		}
	}

	//int a = gold(15);

	for (int i = 2; i <= 1000000; i++)
	{
		if (isPrime[i] == false && i % 2 == 1)
		{
			if (!gold(i))
			{
				cout << i << endl;
				break;
			}
		}
	}
	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: