我是 Java 新手(使用 Pascal 编程),我需要编写一个程序来解决以下问题(类似于数字谜题):
AB + CC = DC
CE * FB = CEB
FF * GC = GHC
AB - CE = FF
CC + FB = GC
DC + CEB = GHC
附言 每个字符都是一个数字(从 0 到 9)。每个数字只能使用一次。
所以我写了下面的程序:
public class javaapplication1 {
public static void main(String[] args) {
boolean bb=false;
for (int h = 0; h < 10; h++) {
for (int g = 0; g < 10; g++) {
if (bb) {
break;
}
for (int f = 0; f < 10; f++) {
if (bb) {
break;
}
for (int e = 0; e < 10; e++) {
if (bb) {
break;
}
for (int d = 0; d < 10; d++) {
if (bb) {
break;
}
for (int c = 0; c < 10; c++) {
if (bb) {
break;
}
for (int b = 0; b < 10; b++) {
if (bb) {
break;
}
for (int a = 0; a < 10; a++) {
if (a*10 + b + c*10 + c == d*10 + c) {
if ((c*10+e)*(f*10+b)==(c*100+e*10+b)) {
if ((f*10+f)*(g*10+c)==g*100+h*10+c) {
if ((a*10+b)-(c*10+e) == f*10+f) {
if ((c*10+c)+(f*10+b) == g*10+c) {
if ((d*10+c)+(c*100+e*10+b) == g*100+h*10+c) {
if (a!=b && a!=c && a!=d && a!=e && a!=f && a!=g && a!=h) {
if (b!=c && b!=d && b!=e && b!=f && b!=g && b!=h) {
if (c!=d && c!=e && c!=f && c!=g && c!=h) {
if (d!=e && d!=f && d!=g && d!=h) {
if (e!=f && e!=g && e!=h) {
if (f!=g && f!=h) {
if (g!=h) {
bb = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
System.out.println(g);
System.out.println(h);
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
它工作并产生正确的结果,但我确信它拼写错误,因为解决方案本身是愚蠢的 - 纯粹的贿赂。请告诉我如何优化这个程序。Z.Y. 为了让我自己的代码更清晰,我在更大程度上写了大量的 if-s。
break通过布尔变量进行复杂化。够return了,它会打破所有循环。10!/2!=10*9*8*7*6*5*4*3支票,没有10^8。“只是为了好玩”的解决方案,但考虑到并行化,在性能方面甚至更好: