第五届蓝桥杯省赛解题报告--神奇算式

来源:互联网 发布:淘宝卖家国际转运服务 编辑:程序博客网 时间:2024/05/17 08:45


标题:神奇算式


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


    比如: 


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


    都符合要求。


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


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


思路分析:

    外层循环遍历所有的四位数,如果该四位数各位数字各不相同,就一次寻找第一个乘数为1为数、第一个乘数为两位数的情况。

代码如下:

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位数,不能为0continue;// 判断商能否被第一个数整除,并将两个乘数的各位数字放到数组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) // 第一个乘数十位数不能为0continue;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 + "种");}}

答案输出:

6x201=1206
6x210=1260
21x60=1260
15x93=1395
35x41=1435
3x501=1503
3x510=1530
30x51=1530
21x87=1827
27x81=2187
9x351=3159
8x473=3784
12种


1 0