Write a program that finds and displays all pairs of 5-digit numbers that between them use the digits 0
through 9 once each, such that the first number divided by the second is equal to an integer N, where
2 ≤ N ≤ 79. That is,
abcde
fghij = N
where each letter represents a different digit. The first digit of one of the numerals is allowed to be
zero.
Input
Each line of the input file consists of a valid integer N. An input of zero is to terminate the program.
Output
Your program have to display ALL qualifying pairs of numerals, sorted by increasing numerator (and,
of course, denominator).
Your output should be in the following general form:
xxxxx / xxxxx = N
xxxxx / xxxxx = N
.
.
In case there are no pairs of numerals satisfying the condition, you must write ‘There are no
solutions for N.’. Separate the output for two different values of N by a blank line.
Sample Input
61
62
0
Sample Output
There are no solutions for 61.
79546 / 01283 = 62
94736 / 01528 = 62
比较水的枚举题,但是事先分析一下也可以使效率提高不少
首先这里有一个printf输出的技巧
%nd 输出的int宽度至少为n位,右对齐,(左对齐则在%后加一个负号)
%5d即宽度至少为5位,位数大于5则输出实际位数,不足5位则用空格填充
%0nd,表示输出int宽度至少为n位,不足n位用0填充
有了这个基础,可以进行下一步分析了,枚举int fghij便可以得到int abcde,我们没有必要枚举10!次
同时我们也没有必要把int fghij从1234枚举到98765,因为fghij是递增的,当int abcde和int fghij加起来超过10位时我们便可终止枚举。如何判断是否超过10位呢? 用strlen(),这样我们就需要使用sprintf将两个int格式化输出至字符串中然后进行判断。注意sprintf中的参数同样也应该是%05d,将2个int输出至字符串之后我们可以将其每个字符排序然后利用ASCII的连续性一次性判断是否有重复的数字 以下是代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
// freopen("datain.txt","r",stdin);
int n,kase=0;char buf[99];
while(~scanf("%d",&n)){
if(!n)break;
int cnt=0;
if(kase++) printf("\n");
for(int fghij=1234;;fghij++){
int abcde=n*fghij;
sprintf(buf,"%05d%05d",abcde,fghij);
if(strlen(buf)>10)break;
sort(buf,buf+10);
bool ok=true;
for(int i=0;i<10;i++){
if(buf[i]!='0'+i)ok=false;
}
if(ok)cnt++,printf("%05d / %05d = %d\n",abcde,fghij,n);
}
if(!cnt) printf("There are no solutions for %d.\n", n);
}
}