• 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;
    	}
    	
    }
    
  • 相关阅读:
    17.07.28 SQL 函数
    JavaScript 数组去重
    JavaScript 之 DOM
    JavaScript 之 BOM
    JavaScript之Math
    JavaScript之String
    JavaScript之数组
    JavaScript之作用域
    JavaScript之函数
    JavaScript之循环
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13076742.html
Copyright © 2020-2023  润新知