您的位置:首页 > 其它

第四届蓝桥杯预赛:马虎的算式

2015-03-24 19:36 260 查看
标题: 马虎的算式

小明是个急性子,上小学的时候经常把老师写在黑板上的题目抄错了。

有一次,老师出的题目是:36 x 495 = ?

他却给抄成了:396 x 45 = ?

但结果却很戏剧性,他的答案竟然是对的!!

因为 36 * 495 = 396 * 45 = 17820

类似这样的巧合情况可能还有很多,比如:27 * 594 = 297 * 54

假设 a b c d e 代表1~9不同的5个数字(注意是各不相同的数字,且不含0)

能满足形如: ab * cde = adb * ce 这样的算式一共有多少种呢?

请你利用计算机的优势寻找所有的可能,并回答不同算式的种类数。

满足乘法交换律的算式计为不同的种类,所以答案肯定是个偶数。

解法1:多层循环

#include <iostream>
using namespace std;
int main()
{
	int a,b,c,d,e,count=0;
	for(a=1;a<=9;a++)
		for(b=1;b<=9;b++)
			for(c=1;c<=9;c++)
				for(d=1;d<=9;d++)
					for(e=1;e<=9;e++)
					{
						if((a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e)&&((a*10+b)*(c*100+d*10+e)==(c*10+e)*(a*100+d*10+b)))
							count++;		
					}
	cout<<count;
	return 0;
}
解法2:排列组合
public class 马虎的算式 {

	public static int[] num = new int[6];
	public static boolean[] visible = new boolean[10];
	public static int count=0;// 记录种数

	public static void check() {
		int ab = num[1]*10+num[2];
		int cde = num[3]*100+num[4]*10+num[5];
		int adb = num[1]*100+num[4]*10+num[2];
		int ce = num[3]*10+num[5];
		if(ab*cde==adb*ce) {
			count++;
		}
	}

	public static void dfs(int cur) {
		if (cur == 6) {
			check();
		} else {
			for (int i = 1; i <= 9; i++) {
				if (visible[i] == false) {
					num[cur] = i;
					visible[i] = true;
					dfs(cur + 1);
					visible[i] = false;
				}
			}
		}
	}

	public static void main(String[] args) {
		dfs(1);
		System.out.println(count);
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: