标签:
除法
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 . 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.
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.
61
62
0
There are no solutions for 61. 79546 / 01283 = 62 94736 / 01528 = 62
题意:
输入正整数n,按从小到大的顺序输出所有形如abcde/fghij=n的表达式,其中a-j恰好为数字0-9的一个排列(可以有前导0), 。
分析:
1.枚举fghij就可以算出abcde,只需遍历所有的分子即可
2.判断是否所有数字都不相同,数字最大为98765,最小为1234.
3.当abcde和fghij加起来超过10位时可以终止枚举
4.暴力求解
代码:
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 5 bool tese(int i,int j) //用数组a存放i,j的各位数字 6 { 7 int a[10]={0}; //初始化数组a,使得各位数字为0,使fghij<10000 时f位置为0 8 int t=0; 9 while(i) //取i中各位数字存放在数组a中 10 { 11 a[t++]=i%10; 12 i=i/10; 13 } 14 while(j) //取j中各位数字存放在数组a中 15 { 16 a[t++]=j%10; 17 j=j/10; 18 } 19 //判断a~j是否恰好为数字的0~9的一个排列 20 for(int m=0;m<=10;++m) 21 for(int n=m+1;n<10;++n) 22 if(a[n]==a[m]) 23 return 0; 24 return 1; 25 } 26 int main() 27 { 28 int n,k,s=0; 29 while(scanf("%d",&n)&&n>=2&&n<=79) 30 { 31 if(s++) //输出一行空行 32 cout<<endl; 33 int count=0; 34 for(k=1234;k<=98765;k++) 35 { 36 int l=k*n; 37 if(l<100000) 38 { 39 if(tese(l,k)) 40 { 41 printf("%05d / %05d = %d\n",l,k,n); 42 count=1; 43 } 44 } 45 else if(l>100000&&count!=1) 46 { 47 printf("There are no solutions for %d.\n",n); 48 break; 49 } 50 } 51 } 52 return 0; 53 }
心得:
以前只是听过用暴力方法解题的,不知道暴力是什么,现在真正用到暴力,发现暴力确实很简单。继续暴力吧。
标签:
原文地址:http://www.cnblogs.com/ttmj865/p/4684939.html