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?
Answer:
296962999629
1、利用『次数表示法』为每个数字增加一种数字表示方式
2、优先按照每个数字的『次数表示数』排序
3、当『次数表示数』相同时,按照数字的原始大小排序4、在重新排好序的数组中,找到满足题目要求的素数序列
次数表示法:
1、将一个整型N映射成为另外一个整型M
2、M中的第i位代表整型N的十进制表示中数字i出现的次数
3、根据题目,由于i出现的次数最多是3次,所以每位需要两个二进制位
#include<bits/stdc++.h>
using namespace std;
#define maxn 500005
bool is_prime[maxn];
int binnum[maxn];
vector<int> prime;
struct node{
int num;
int bnum;
}d[maxn];
int dlen=0;
int change(int n) //转换为二进制标记
{
int ret=0;
while(n)
{
ret+=1<<(2*(n%10));
n/=10;
}
return ret;
}
void init()
{
memset(is_prime,1,sizeof(is_prime));
for(int i=2;i<maxn;i++)
{
if(is_prime[i]) {
prime.push_back(i);
if(i>1000)
{
d[dlen].num=i;
d[dlen].bnum=change(i);
binnum[i]=d[dlen].bnum;
dlen++;
}
}
for(int j=0;i*prime[j]<maxn;j++)
{
is_prime[i*prime[j]]=0;
if(i%prime[j]==0) break;
}
}
}
bool cmp(node a,node b)
{
return a.bnum==b.bnum?a.num<b.num:a.bnum<b.bnum;
}
int main()
{
init();
sort(d,d+dlen,cmp);
for(int i=0;i<dlen-3;i++)
{
for(int j=i+1;d[i].bnum==d[j].bnum;j++) {
int thnum=2*d[j].num-d[i].num;
if(thnum>=10000) break;
if(!is_prime[thnum]) continue;
if(binnum[thnum]==d[i].bnum) {
cout<<d[i].num<<d[j].num<<thnum<<endl;
// system("pause");
}
}
}
}