Project Euler:Problem 51 Prime digit replacements

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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值