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
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//140msAC #include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> using namespace std; bool com(char a,char b){ return a>b; } char ans[11]="9876543210"; char s[11]; int main(){ int n,pro,m=0; bool flag; while(scanf("%d",&n)!=EOF&&n){ if(m>0) printf("\n"); m++; flag=false; for(int i=1234;i<50000;i++){ pro=n*i; if(pro>98765) break; if(i<10000) sprintf(s,"%d%d%d",0,i,pro); else sprintf(s,"%d%d",i,pro); sort(s,s+10,com); if(strcmp(s,ans)==0){ printf("%d / %05d = %d\n",pro,i,n); flag=true; } } if(!flag) printf("There are no solutions for %d.\n",n); } return 0; }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//20ms #include<iostream> #include<string.h> using namespace std; int x[10]; int main(){ int a,b,c,d,e; int f,g,h,i,j; int k,l,m,n,s=0,t; while(cin>>n&&n){ if(s==0) s=1; else cout<<endl; t=0; for(k=1234;k<50000;k++){ m=k*n; if(m>98765) break; a=m/10000; b=m/1000%10; c=m/100%10; d=m/10%10; e=m%10; f=k/10000; g=k/1000%10; h=k/100%10; i=k/10%10; j=k%10; memset(x,0,sizeof(x)); x[a]++;x[b]++;x[c]++;x[d]++;x[e]++; x[f]++;x[g]++;x[h]++;x[i]++;x[j]++; for(l=0;l<10;l++){ if(x[l]>1) break; } if(l==10){ t=1; cout<<a<<b<<c<<d<<e<<" / "<<f<<g<<h<<i<<j<<" = "<<n<<endl; } else{ continue; } } if(t==0) { cout<<"There are no solutions for "<<n<<"."<<endl; } } return 0; }
【分析】
很多问题都可以“暴力解决”——不用动太多脑筋,把所有可能性都列举出来,然后一一试验。尽管这样的方法显得很“笨”,但却常常是行之有效的。枚举fghij就可以算出abcde,并且所有数字不相同即可。
注意:开关的初始化和格式问题( two different values of N by a blank line.)。