UVA725

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);
   }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值