PAT2019秋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.

思路

题意是给出数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;
} 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值