PAT 1160 Forever
PAT(甲级)2019年秋季考试 (第一题)
7-1 Forever (20 分)
“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.
Sample Input:
2
6 45
7 80
Sample Output:
Case 1
10 189999
10 279999
10 369999
10 459999
10 549999
10 639999
10 729999
10 819999
10 909999
Case 2
No Solution
看起来很简单,但实际有坑的一道题,主要考数学常识。如果直接从给个某个位数到下一位数找必定最后一个测试点超时,因为二者之间存在很多根本不可能满足要求的数,对它们求公约数浪费大量时间。假定两个数1087,1088,显然这两位的m=16和n=17只相差1,最大公约数只能为1,同理1089和1090的m=18和n=10只相差8,对于这一类,最大公约数只能为1,2,4,8,而1099的m和n相差为17,因此能满足要求的尾数至少为99。
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int sumdigit(int x) {
return !x?0:sumdigit(x/10) + x%10;
}
int gcd(int a, int b) {
return !b?a:gcd(b, a%b);
}
bool isprime(int x){
if (x<=3) return false;
int sqr=sqrt(x);
for(int i=2; i<=sqr; i++) {
if (x%i==0) return false;
}
return true;
}
struct node{
int n, num;
};
bool cmp(const node &a, const node &b) {
if (a.n!=b.n) return a.n<b.n;
return a.num<b.num;
}
int main() {
int N, a, b, x, y, m, n;
scanf("%d", &N);
for (int i=1; i<=N; i++) {
scanf("%d%d", &a, &m);
printf("Case %d\n", i);
x=pow(10, a-1);
y=x*10;
vector<node> vi;
for (int j=x; j<y; j++) {
if (j%100!=99) continue;
if (sumdigit(j)==m) {
n=sumdigit(j+1);
if (isprime(gcd(n, m))) {
vi.push_back(node{n, j});
}
}
}
sort(vi.begin(), vi.end(), cmp);
for (auto &i: vi){
printf("%d %d\n", i.n, i.num);
}
if (vi.empty()) printf("No Solution\n");
}
return 0;
}