蓝桥杯,最大比例JAVA

该篇博客展示了如何使用Java实现快速求两个长整型数的最大公约数,并利用排序后的数组进行特定操作。通过gcd和qgcd函数,作者探讨了如何找到数组中两数的商和余数序列。最后,文章关注于计算这些序列的最小公倍数并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		scanner.nextLine();
		Set<Long> set = new HashSet<>(); 
		for(int i = 0; i < n; i++) {
			set.add(scanner.nextLong());
		}
		n = set.size();
		Iterator<Long> iterator = set.iterator();
		int o = 0;
		long[] temp = new long[n];
		while(iterator.hasNext()) {
			temp[o++] = iterator.next();
		}
		Arrays.sort(temp);
		long[] q1 = new long[n-1];
		long[] q2 = new long[n-1];
		for(int i = 0; i < n-1; i++) {
			long x = gcd(temp[i+1],temp[i]);
			q1[i] = temp[i+1]/x;
			q2[i] = temp[i]/x;
		}
		Arrays.sort(q1);
		Arrays.sort(q2);
		long ans1=q1[0],ans2=q2[0];
	    for(int i=1;i<=n-2;i++){
	        ans1=qgcd(ans1,q1[i]);
	        ans2=qgcd(ans2,q2[i]);
	    }
		System.out.println(ans1 + "/" + ans2);
	}
	
	public static long qgcd(long a,long b){
	    if(a==b)
	        return a;
	    return qgcd(Math.min(b/a,a), Math.max(b/a,a));
	}
	
	public static long gcd(long a, long b) {
		if(0 == a) return b;
		if(0 == b) return a;
		if(a<b) {
			long c = a;
			a = b;
			b = c;
		}
		for(long c = a%b; c > 0; c = a%b) {
			a = b;
			b = c;
		}
		return b;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值