天天看点

UVA725 UVALive5362 Division【暴力+进制】

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,

UVA725 UVALive5362 Division【暴力+进制】

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

Sample Output

There are no solutions for 61.

79546 / 01283 = 62

94736 / 01528 = 62

Regionals 1990 >> North America - East Central NA

问题链接:UVA725 UVALive5362 Division。

题意简述:

  输入正整数n,用0~9这10个数字不重复组成两个五位数abcde和fghij,使得abcde/fghij的商为n,按顺序输出所有结果。如果没有找到则输出“There are no solutions for N.”。这里2<=n<=79。

问题分析:

  没有什么好办法,就暴力枚举吧!不过还是要下点功夫,否则10!的计算量是不可想象的。

  1.因为n>=2,且abcde=fghij×n,满足abcde>fghij。若a=0,则fghij的最小值为12345,abcde<fghij,矛盾。所以a≠0。

  2.因为a≠0,所以12345<=abcde<=98765,01234<=fghij。

  3.因为2≤n,且abcde≤98765,那么fghij = abcde/n,得fghij≤98765/2=49382,所以01234≤fghij≤49382。

  4.因为12345≤abcde≤98765,且01234≤fghij≤49382,所以用fghij进行枚举范围比较小。(这是在任意的n的条件下得出的结论)

  5.对于给定的n,因为abcde≤98765,那么fghij = abcde/n,得fghij≤98765/n。结论:01234≤fghij≤98765/n。

程序说明:

  这可以说是最快枚举程序,比网上现有的暴力枚举程序要快。

AC的C语言程序如下:

/* UVA725 UVALive5362 Division */

#include <stdio.h>
#include <memory.h>

#define DIGITNUM 10

int check(int abcde, int fghij)
{
    int used[DIGITNUM], d;

    memset(used, 0, sizeof(used));

    if(fghij < 10000)
        used[0] = 1;

    while(abcde) {
        d = abcde % 10;
        if(used[d])
            return 0;
        used[d] = 1;

        abcde /= 10;
    }

    while(fghij) {
        d = fghij % 10;
        if(used[d])
            return 0;
        used[d] = 1;

        fghij /= 10;
    }

    return 1;
}

int main(void)
{
    int n, abcde, count, caseflag=0, end, i;

    while(scanf("%d", &n) != EOF && n != 0) {
        if(caseflag)
            printf("\n");
        caseflag = 1;

        count = 0;
        end = 98765 / n;
        for(i=1234; i<=end; i++) {
            abcde = i * n;
            if(abcde >= 12345 && check(abcde, i)) {
                printf("%05d / %05d = %d\n", abcde, i, n);
                count++;
            }
        }
        if(count == 0)
            printf("There are no solutions for %d.\n", n);
    }

    return 0;
}
           

继续阅读