Java实现 洛谷 P2118 比例简化

在这里插入图片描述

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
 
public class Main {
	private static Scanner cin;
 
	public static void main(String args[])  {
		cin = new Scanner(System.in);
		int a = cin.nextInt();
		int b = cin.nextInt();
		int l = cin.nextInt();
		float AB = (float)a/(float)b;
		int retA = 1;
		int retB = 1;
		float minDifferenceValue = -1;
		for(int i = 1; i<=l;i++) {
			for(int j=1;j<=l;j++) {
				float tmp = (float)i/(float)j;
				float differenceValue = tmp-AB;
				if(tmp>= AB & getGreatestCommonDivisor(i,j)==1) {
					if(minDifferenceValue == -1 || differenceValue < minDifferenceValue) {
						retA = i;
						retB = j;
						minDifferenceValue = differenceValue;
					}
				}
			}
		}
		
		System.out.println(String.format("%d %d", retA,retB));
	}
	
	
	
	private static int getGreatestCommonDivisor(int n1, int n2) {
		int num1 = n1;
		int num2 = n2;
		if(num1<num2){
            int temp=num1;
            num1=num2;
            num2=temp;
        }
 
        int remainder = num1%num2;
 
        while(remainder!=0){
            num1=num2;
            num2=remainder;
            remainder=num1%num2;
        }
        return num2;
	}
	
}
posted @ 2019-07-30 18:44  南墙1  阅读(18)  评论(0编辑  收藏  举报