蓝桥杯:奇怪的分式JAVA

标题:奇怪的分式

上小学的时候,小明经常自己发明新算法。一次,老师出的题目是:
1/4 乘以 8/5
小明居然把分子拼接在一起,分母拼接在一起,答案是:18/45 (参见图1.png)
老师刚想批评他,转念一想,这个答案凑巧也对啊,真是见鬼!
对于分子、分母都是 1~9 中的一位数的情况,还有哪些算式可以这样计算呢?
请写出所有不同算式的个数(包括题中举例的)。
显然,交换分子分母后,例如:4/1 乘以 5/8 是满足要求的,这算做不同的算式。
但对于分子分母相同的情况,2/2 乘以 3/3 这样的类型太多了,不在计数之列!
注意:答案是个整数(考虑对称性,肯定是偶数)。请通过浏览器提交。不要书写多余的内容。

在这里插入图片描述

思路解析:

利用全排列中的思路和模板,这道题也就是在所有数字组合找到像图中既能数字组合在一起和直接计算乘除相等的数字

代码解析:

public static void backtrack(List<List<Integer>>end,List<Integer>list,int nums[]) {
		if (list.size() == 4) {
			end.add(new ArrayList<Integer>(list));
		}
		for(int num:nums) {
			if (!list.contains(num)) {
				list.add(num);
				backtrack(end, list, nums);
				list.remove(list.size()-1);
			}
		}
	}
	public static int judge(int a,int b) {
		int c = a%b;
		while(c!= 0) {
			a = b;
			b = c;
			c = a%b;
		}
		return b;
	}
	public static void prum(){
		int[]nums = new int[9];
		int j = 1;
		for (int i = 0;i < 9;i++,j++) {
			nums[i] = j;
		}
		List<List<Integer>>end = new ArrayList<List<Integer>>();
		List<Integer>list = new ArrayList<Integer>();
		backtrack(end, list, nums);
		int m;
		for (j = 0;j < end.size();j++) {
			list = end.get(j);
			int fenzi1 = list.get(0);
			int fenzi2 = list.get(1);
			int fenmu1 = list.get(2);
			int fenmu2 = list.get(3);
			int a = fenzi1*10+fenzi2;
			int b  = fenmu1*10+fenmu2;
			int end1,end2;
			int c = judge(a,b);
			a = a/c;
			b = b/c;
			end1 = fenzi1*fenzi2;
			end2 = fenmu1*fenmu2;
			c = judge(end1, end2);
			end1 /= c;//分子
			end2 /= c;//分母
			if (a==end1&&b==end2) {
				System.out.println(list);
			}
		}
		
	}
	public class test {
			public static void main(String[] args) {
				prum();	
			}
	}

OUT:
[1, 4, 6, 3]
[1, 5, 2, 4]
[1, 8, 4, 5]
[2, 4, 1, 5]
[4, 5, 1, 8]
[6, 3, 1, 4]

漏点总结:

end.add(new ArrayList<Integer>(list))

当最后传入时候list已经存在,此处为直接将list加入end列表中

此题涉及了最大公约数的求解,对此方面有些薄弱,需要加强

发布了9 篇原创文章 · 获赞 0 · 访问量 62

猜你喜欢

转载自blog.csdn.net/weixin_44575373/article/details/104774120
今日推荐