Description:

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
\le N \le 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.

 

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

解析:通过枚举除数fghij可以算出abcde,然后将这几个数字字符排序一下查找是否所有数字都不相同。特别注意的是:当ab
cde+fghij超过十位时可以终止枚举。
代码如下:
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 using namespace std;
 6 
 7 int main() 
 8 {
 9     int n, k= 0;
10     char buf[99];
11     while(scanf("%d", &n) == 1 && n) 
12     { 
13         
14         int cnt = 0;
15         if(k++) 
16             printf("\n");
17         for(int fghij = 1234; ; fghij++)
18         {
19             int abcde = fghij * n;   //通过枚举fghij的值确定abcde的值
20             sprintf(buf, "%05d%05d", abcde, fghij);  //将这两个字符格式化
21             if(strlen(buf) > 10)  //  循环终止条件:abcde+fghij大于十位
22                 break;
23             sort(buf, buf+10);    //排序后,方便剔除有重复数字的buf。
24             bool ok = true;
25             for(int i = 0; i < 10; i++)
26                 if(buf[i] != '0' + i) 
27                     ok = false;    
28                 if(ok) 
29                 {
30                     cnt++;
31                     printf("%05d / %05d = %d\n", abcde, fghij, n);  //输出格式要格外注意!!
32                 }
33         }
34         if(!cnt) 
35             printf("There are no solutions for %d.\n", n);
36     }
37     return 0;
38 }
注意暴力解题时要认真分析,避免枚举过多超内存。

 



posted on 2015-08-02 14:58  xx-sisley  阅读(433)  评论(0编辑  收藏  举报