Project Euler:Problem 49 Prime permutations

The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.

What 12-digit number do you form by concatenating the three terms in this sequence?



用了个超级麻烦的方法做出来了,先求出质数列表,再求出全排列,再找出符合条件的数。开始的时候还把等比数列这个条件忘记了,难怪输出结果那么多。


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

bool isPrime[10000];
int cnt = 0;
vector<int>tp;

void perm(int list[], int n, int k)
{
	int temp1, temp2;
	if (n == 0)
	{
		if (list[k] != 0)
		{
			int sum = 0;
			for (int i = 0; i <= k; i++)
				sum = sum * 10 + list[i];
			if (sum >= 1000 && sum < 10000)
			{
				if (isPrime[sum])
				{
					if (find(tp.begin(), tp.end(), sum) == tp.end())
					{
						cnt++;
						tp.push_back(sum);
					}
				}
			}
		}
	}
	else
	{
		for (int i = 0; i <= n; i++)
		{
			temp1 = list[i];
			list[i] = list[n];
			list[n] = temp1;

			perm(list, n - 1, k);

			temp2 = list[i];
			list[i] = list[n];
			list[n] = temp2;
		}
	}
}


bool ok(int n)
{
	int a[4];
	int count = 0;
	int num = n;
	while (n)
	{
		a[count++] = n % 10;
		n /= 10;
	}
	cnt = 0;
	tp.clear();
	tp.push_back(num);
	perm(a, 3, 3);
	if (cnt >= 3)
		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 < 10000; j++)
			{
				isPrime[i*j] = false;
			}
		}
	}

	for (int i = 1000; i < 10000; i++)
	{
		if (isPrime[i])
		{
			if (ok(i))
			{
				int b[3];
				b[0] = tp[0];
				b[1] = tp[1];
				b[2] = tp[2];
				sort(b, b + 3);
				if (b[2] - b[1] == b[1] - b[0])
					cout << b[0] << b[1] << b[2] << endl;
			}
		}
	}
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值