您的位置:首页 > 其它

Project Euler:Problem 51 Prime digit replacements

2015-07-01 19:58 459 查看
By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers,
yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.

对于满足这种条件的family,它们的关系类似一种等差数列
比如说56003与56113相差110,然后56113与56333相差110*2
所以我的方法是先求出1000000以内的质数,然后按从小到大的顺序找出有相同数位的质数,找出里面的等差值,然后加上等差值,检查是否为质数,若为质数,count++;无论是否为质数,继续加上等差值,直到那个相同数位上的数为9时停止,查看count的值。为8时,原来最初的那个数就是要求的。

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

bool isPrime[1000010];
int ans = 0;

void getprime()            //获得1000000以内的质数
{
	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;
			}
		}
	}
}

bool same_num(int n)
{
	map<int, vector<int>>mp;
	int count = 0;
	int num = n;
	while (n)
	{
		mp[n % 10].push_back(count);
		n /= 10;
		count++;
	}
	
	int ok = 0;
	map<int, vector<int>>::iterator iter;
	for (iter = mp.begin(); iter != mp.end(); iter++)
	{
		if (iter->second.size() < 2)
			ok++;
	}
	if (ok == mp.size())
		return false;

	
	for (iter = mp.begin(); iter != mp.end(); iter++)
	{
		if (iter->second.size() >= 2)
		{
			if (iter->first <= 2)
			{
				int gap = 0;
				for (int k = 0; k < iter->second.size(); k++)
				{
					gap += pow(10, iter->second[k]);
				}
				int p_count = 1;
				int c_num = num;
				for (int k = 1; k < 10-iter->first; k++)
				{
					if (isPrime[num + gap*k])
						p_count++;
				}
				if (p_count == 8)
				{
					ans = num;
					return true;
				}
			}

		}
	}
	return false;
}

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