java實現第五屆藍橋杯神奇算式

神奇算式

題目描述
由4個不一樣的數字,組成的一個乘法算式,它們的乘積仍然由這4個數字組成。java

好比:數組

210 x 6 = 1260
8 x 473 = 3784
27 x 81 = 2187瀏覽器

都符合要求。ide

若是知足乘法交換律的算式算做同一種狀況,那麼,包含上邊已列出的3種狀況,一共有多少種知足要求的算式。code

請填寫該數字,經過瀏覽器提交答案,不要填寫多餘內容(例如:列出全部算式)。排序

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 + "種");
	}
}
相關文章
相關標籤/搜索