枫林在线论坛精华区>>程序设计 |
[323167] 主题: 一道程序题 |
作者: little (渺小·Happy^_^) | ||
标题: 一道程序题 | ||
来自: 192.168.*.* | ||
发贴时间: 2005年01月18日 12:49:22 | ||
长度: 2802字 | ||
题目:
使用1-8这8个数字,组成abc*d=efgh或者ab*cd=efgh形式的等式。要 求,每个数字被使用1次。求出所有不重复的解。 解答一(VB) 比较容易想到但十分繁琐的解题思路 Dim i, j, k, l, m, n, o, p As Integer For i = 1 To 8 For j = 1 To 8 Do While j = i And j < 8 j = j + 1 Loop For k = 1 To 8 Do While (k = j Or k = i) And k < 8 k = k + 1 Loop For l = 1 To 8 Do While (l = k Or l = j Or l = i) And l < 8 l = l + 1 Loop For m = 1 To 8 Do While (m = l Or m = k Or m = j Or m = i) And m < 8 m = m + 1 Loop For n = 1 To 8 Do While (n = m Or n = l Or n = k Or n = j Or n = i) And n < 8 n = n + 1 Loop For o = 1 To 8 Do While (o = n Or o = m Or o = l Or o = k Or o = j Or o = i) A nd o < 8 o = o + 1 Loop For p = 1 To 8 Do While (p = o Or p = n Or p = m Or p = l Or p = k Or p = j Or p = i) And p < 8 p = p + 1 Loop If p <> o And p <> n And p <> m And p <> l And p <> k And p <> j And p <> i And o < > n And o <> m And o <> l And o <> k And o <> j And o <> i And j <> i And k <> j An d k <> i And l <> k And l <> j And l <> i And m <> l And m <> k And m <> j And m <& gt; i And n <> m And n <> l And n <> k And n & lt;> j And n <> i Then If (i * 100 + j * 10 + k) * l = m * 1000 + n * 100 + o * 10 + p Then Print i; j; k; "*"; l; "="; m; n; o; p ElseIf (i * 10 + j) * (k * 10 + l) = m * 1000 + n * 100 + o * 10 + p And i * 10 + j < k * 10 + l Then Print i; j; "*"; k; l; "="; m; n; o; p End If End If Next p Next o Next n Next m Next l Next k Next j Next i 解答二(C) 一种效率较高但比较难理解的解题思路 #include <stdio.h> #define MAX_DIGIT 8 #define BUFFER_LEN 9 int main () { int i, pos = 0, digit[BUFFER_LEN], result[BUFFER_LEN]; int x, y, z; for (i = 0; i < BUFFER_LEN; i++) digit[i] = 0; for (i = 0; i < BUFFER_LEN; i++) result[i] = 0; while (pos >= 0) { //Search available digit for (i = result[pos] + 1; i <= MAX_DIGIT; i++) { if (digit[i] == 0) { digit[result[pos]] = 0; digit[i] = 1; result[pos++] = i; i = result[pos]; if (pos == MAX_DIGIT) { //abc * d = efgh x = result[0] * 100 + result[1] * 10 + result[2]; y = result[3]; z = result[4] * 1000 + result[5] * 100 + result[6] * 10 + result[7]; if (x * y == z) printf ("%d * %d = %dn", x, y, z); //ab * cd = efgh x = result[0] * 10 + result[1]; y = result[2] * 10 + result[3]; if ((x <= y) && (x * y == z)) printf ("%d * %d = %dn", x, y, z); pos--; } } } if (pos == 0) break; digit[result[pos]] = 0; result[pos--] = 0; } return 0; } 个人推荐使用C语言实现的那种方法,不过实在不懂的用VB的那种也可 以。 -- ※作者已于 2005-01-18 18:28:10 修改本文※ |
||
========== * * * * * ==========
|
返回 |