"Forever number" is a positive integer A with K digits, satisfying the following constrains:
- the sum of all the digits of A is m;
- the sum of all the digits of A+1 is n; and
- the greatest common divisor of m and n is a prime number which is greater than 2.
Now you are supposed to find these forever numbers.
Input Specification:
Each input file contains one test case. For each test case, the first line contains a positive integer N (≤5). Then N lines follow, each gives a pair of K (3<K<10) and m (1<m<90), of which the meanings are given in the problem description.
Output Specification:
For each pair of K and m, first print in a line Case X
, where X
is the case index (starts from 1). Then print n and A in the following line. The numbers must be separated by a space. If the solution is not unique, output in the ascending order of n. If still not unique, output in the ascending order of A. If there is no solution, output No Solution
.
思路
题意是给出数x的位数k和各位数总和m,x+1的各位数总和d与m的最大公约数是大于2的质数,要求所有的x,按照d的大小排序,如果不独立,再按x排序。首先,写出常用的函数:最大公约数gcd,判断是否为质数isprime,计算所有位数之和sum,比较函数cmp,用结构体存储满足条件的结果。这题最关键的是,要找到规律:所有满足条件的x末两位数是99,加1不进位的话各位数之和只会有1的大小变化。如果全部遍历,最后一定会超时。遍历时把满足要求的node放入vector中,再排序输出。
代码
#include<stdio.h>
#include<math.h>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int n,k;
};
bool cmp(node a,node b){
if(a.n!=b.n) return a.n<b.n;
else return a.k<b.k;
}
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
bool isprime(int n){
if(n<3) return false;
for(int i=2;i<=(int)sqrt(n);i++){
if(n%i==0) return false;
}
return true;
}
int sum(int n){
return n==0?0:sum(n/10)+n%10;
}
int main(){
int n,k,m,a,b,c,d;
vector<node> v;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d%d",&k,&m);
printf("Case %d\n",i+1);
v.clear();
a=(int)pow(10,k-3);
b=a*10;
for(int j=a;j<b;j++){
c=j*100+99;
d=sum(c+1);
if(sum(c)==m&&isprime(gcd(m,sum(c+1))))
v.push_back({d,c});
}
if(v.empty())
printf("No Solution\n");
else{
sort(v.begin(),v.end(),cmp);
for(auto x:v)
printf("%d %d\n",x.n,x.k);
}
}
return 0;
}