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

Project Euler:Problem 87 Prime power triples

时间:2015-07-23 21:50:50      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:c++   project euler   质数生成   

The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:

28 = 22 + 23 + 24
33 = 32 + 23 + 24
49 = 52 + 23 + 24
47 = 22 + 33 + 24

How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?



先判断数的大致范围:sqrt(50000000)=7081  

求出2~7081之间的所有质数

然后三层循环便利出所有能表示出的50000000以内的整数


#include <iostream> 
#include <string>
#include <map>
using namespace std;

bool isPrime[7081];
int prime[2000];

void judge()
{
	for (int i = 2; i < 7081; i++)
	{
		if (isPrime[i])
		{
			for (int j = i; j*i < 7081; j++)
				isPrime[j*i] = 0;
		}
	}
}

int getPrime()
{
	int count = 0;
	for (int i = 2; i < 7081; i++)
	{
		if (isPrime[i])
		{
			prime[count++] = i;
		}
	}
	return count;
}

int main()
{
	memset(isPrime, true, sizeof(isPrime));
	judge();
	int num = getPrime();
	map<int, int>mp;
	for (int i = 0; i < num; i++)
	{
		int a = prime[i] * prime[i] * prime[i] * prime[i];
		if (a>50000000)
			break;
		for (int j = 0; j < num; j++)
		{
			int b = prime[j] * prime[j] * prime[j];
			if (a + b>50000000)
				break;
			for (int k = 0; k < num; k++)
			{
				int c = prime[k] * prime[k];
				if (a + b + c>50000000)
					break;
				mp[a + b + c]++;
			}
		}
	}

	cout << mp.size() << endl;
	system("pause");
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Project Euler:Problem 87 Prime power triples

标签:c++   project euler   质数生成   

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

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