80分第二个错了,上一个是对的
查看原帖
80分第二个错了,上一个是对的
749028
QAQ5楼主2025/1/2 11:56
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Fraction one = new Fraction(scanner.nextLine()), two = new Fraction(scanner.nextLine());
        Fraction result = mulFraction(one, two);
        System.out.println(result.month + " " + result.son);
    }

    //计算分数结果化简
    static Fraction mulFraction(Fraction one, Fraction two) {
        int mulSon = one.son * two.son, mulMonth = one.month * two.month;
        //除到直到不能被2整除
        while (mulSon % 2 == 0 && mulMonth % 2 == 0) {
            mulSon /= 2;
            mulMonth /= 2;
        }
        //母除子的整除情况不考虑,后来发现没考虑很多,直接算公约数
        int cache;
        if ((cache = commonDivisor(mulSon, mulMonth)) != 1) {
            mulSon /= cache;
            mulMonth /= cache;
        }
        return new Fraction(mulSon, mulMonth);
    }

    //最小公约数
    static int commonDivisor(int num1, int num2) {
        int min = Math.min(num1, num2);
        for (int left = 3; left < min; left += 2) {
            if (num1 % left == 0 && num2 % left == 0)
                return left;
        }
        return 1;
    }
}

class Fraction {
    int son, month;

    public Fraction(int son, int month) {
        this.son = son;
        this.month = month;
    }

    public Fraction(String fraction) {
        String[] two = fraction.split("/");
        String son = two[0], month = two[1];
        this.son = Integer.parseInt(son);
        this.month = Integer.parseInt(month);
    }

    @Override
    public String toString() {
        return month + "/" + son;
    }
}

2025/1/2 11:56
加载中...