题目:
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
题意:
输入N,用0-9 10个数字进行xxxxx / xxxxx = N表示。0可以放在前面,故被除数最小为1234,被除数与N相乘得除数,遍历判定是否符合条件。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int main(){
int n;
char buf[99];
int kase = 0;
while(cin>>n && n){
bool flag = false;
if(kase++)
cout<<endl;
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] != i + '0')
ok = false;
if(ok){
flag = true;
printf("%05d / %05d = %d\n",abcde,fghij,n);
}
}
if(!flag)
printf("There are no solutions for %d.\n", n);
}
return 0;
}
知识点:
1:sprintf的用法:常用于将一串数字赋给一个字符串。
参考链接:http://c.biancheng.net/cpp/html/33.html
注意输出格式除了第一个数,都有换行。