Project Euler:Problem 60 Prime pair sets

The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.



太暴力了不忍心贴代码了(╯‵□′)╯︵┻━┻

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

bool isp[100000000];
int prime[1500];

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

int cnt;
void prim()
{
	int count = 0;
	for (int i = 2; i < 100000000; i++)
	{
		if (isPrime(i))
		{
			isp[i] = 1;
			if (i<10000)
				prime[count++] = i;
		}
	}
	cnt = count;
}

bool check(int a, int b, int c, int d, int e)
{
	int num[5] = { a, b, c, d, e };
	for (int i = 0; i < 5; i++)
	{
		for (int j = 0; j < 5; j++)
		{
			if (i == j)
				continue;

			int tp1 = num[i];
			int tp2 = num[j];
			while (tp2)
			{
				tp1 *= 10;
				tp2 /= 10;

			}
			tp1 += num[j];
			if (isp[tp1] == 0)
				return false;

		}
	}
	return true;
}

bool twocheck(int a, int b)
{
	int tp1 = a;
	int tp2 = b;
	while (tp2)
	{
		tp1 *= 10;
		tp2 /= 10;
	}
	tp1 += b;
	if (isp[tp1])
		return true;
	return false;
}

int main()
{
	memset(isp, 0, sizeof(isp));
	prim();
	int res = 0;
	int flag = 0;
	for (int a = 0; a < cnt; a++)
	{
		if (flag == 1)
			break;
		for (int b = a + 1; b < cnt; b++)
		{
			if (!twocheck(prime[a], prime[b]) || !twocheck(prime[b], prime[a]))
				continue;
			if (flag == 1)
				break;
			for (int c = b + 1; c < cnt; c++)
			{
				if (!twocheck(prime[c], prime[b]) || !twocheck(prime[b], prime[c]) || !twocheck(prime[a], prime[c]) || !twocheck(prime[c], prime[a]))
					continue;
				if (flag == 1)
					break;
				for (int d = c + 1; d < cnt; d++)
				{
					if (!twocheck(prime[d], prime[b]) || !twocheck(prime[b], prime[d]) || !twocheck(prime[a], prime[d]) || !twocheck(prime[d], prime[a])
						|| !twocheck(prime[c], prime[d]) || !twocheck(prime[d], prime[c]))
						continue;
					if (flag == 1)
						break;
					for (int e = d + 1; e < cnt; e++)
					{
						if (check(prime[a], prime[b], prime[c], prime[d], prime[e]))
						{
							res = prime[a] + prime[b] + prime[c] + prime[d] + prime[e];
							cout << res << endl;
							flag = 1;
							break;
						}
					}
				}
			}
		}
	}

	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值