java实现第五届蓝桥杯神奇算式

神奇算式

题目描述
由4个不同的数字,组成的一个乘法算式,它们的乘积仍然由这4个数字组成。

比如:

210 x 6 = 1260
8 x 473 = 3784
27 x 81 = 2187

都符合要求。

如果满足乘法交换律的算式算作同一种情况,那么,包含上边已列出的3种情况,一共有多少种满足要求的算式。

请填写该数字,通过浏览器提交答案,不要填写多余内容(例如:列出所有算式)。

package mec.lanqiao;
 
import java.util.*;
 
public class Main {
	static int cnt = 0;
 
	// 判断一个数组里的元素是否各不相同
	static boolean isBuTong(int[] x) {
		Set<Integer> set = new HashSet<>();
		for (int i = 0; i < x.length; i++) {
			set.add(x[i]);
		}
		return x.length == set.size();
	}
 
	public static void main(String[] args) {
		for (int n = 1000; n < 9999; n++) {
			int[] store = { n / 1000, n / 100 % 10, n / 10 % 10, n % 10 };
			Arrays.sort(store); // 对数组进行排序
			if (isBuTong(store)) { // 各位数字各不相同
 
				// 找较小乘数为1位数字的情况
				for (int i = 0; i < store.length; i++) {
					if (store[i] == 0) // 第一个数字为1位数,不能为0
						continue;
					// 判断商能否被第一个数整除,并将两个乘数的各位数字放到数组nStore中,比较nStore里的元素与store里是否完全相同
					if (n % store[i] == 0 && n / store[i] / 100 < 10) {
						int t = n / store[i];
						int[] nStore = { store[i], t / 100, t / 10 % 10, t % 10 };
						Arrays.sort(nStore);
						boolean f = true;
						for (int j = 0; j < 4; j++) {
							if (store[j] != nStore[j]) {
								f = false;
								break;
							}
						}
						if (f) {
							cnt++; // 相同则cnt加一
							System.out.println(store[i] + "x" + t + "=" + n);
						}
					}
				}
				// 找较小乘数为2位数字的情况
				for (int i = 0; i < store.length; i++) {
					if (store[i] == 0) // 第一个乘数十位数不能为0
						continue;
					for (int j = 0; j < store.length; j++) {
						int first = store[i] * 10 + store[j]; // 第一个乘数
						if (n % first == 0 && n / first / 10 < 10) {
							int sec = n / first; // 第二个乘数
							int[] nStore = { store[i], store[j], sec / 10,
									sec % 10 };
							Arrays.sort(nStore);
							boolean f = true;
							for (int k = 0; k < nStore.length; k++) {
								if (store[k] != nStore[k]) {
									f = false;
									break;
								}
							}
							if (f && first <= sec) {
								cnt++; // 相同则cnt加一
								System.out.println(first + "x" + sec + "=" + n);
							}
						}
					}
				}
			}
		}
		System.out.println(cnt + "种");
	}
}
原文地址:https://www.cnblogs.com/a1439775520/p/12947559.html