question:相遇周期

杭电oj_1713——相遇周期(java实现)-LMLPHP

思路:

首先将两个分数化为最简形式(也就是分子分母同时除以最大公约数)

然后题意是要求两个分数的最小公倍数

借助以下两个公式,就可以求出结果

1.最小公倍数*最大公约数 = a*b

2.两个分数的最小公倍数:分子为两个分子的最小公倍数,分母为两个分母的最大公约数(前提是分数是最简形式)

注:最后结果要判断一下,如果分子可以被分母整除,则只要输出整除的结果,否则输出拼接字符串

source code:

package hduoj;

import java.util.Scanner;

/**
* 最小公倍数*最大公约数 = a*b
* 两个分数的最小公倍数:分子为两个分子的最小公倍数,分母为两个分母的最大公约数(前提是分数是最简形式
*/
public class hdoj_1713 {
static long gcd(long a,long b){
if(b==0) return a;
return(gcd(b,a%b));
} public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = Integer.parseInt(sc.next());
while(count--!=0){
String the_first = sc.next();
String the_last = sc.next();
long the_first_numberator = Integer.parseInt(the_first.split("/")[0]);
long the_first_denominator = Integer.parseInt(the_first.split("/")[1]);
long gcd_1 = gcd(the_first_numberator,the_first_denominator);
the_first_numberator/=gcd_1;
the_first_denominator/=gcd_1; long the_last_numberator = Integer.parseInt(the_last.split("/")[0]);
long the_last_denominator = Integer.parseInt(the_last.split("/")[1]);
long gcd_2 = gcd(the_last_numberator,the_last_denominator);
the_last_numberator/=gcd_2;
the_last_denominator/=gcd_2; long gcd_3 = gcd(the_first_numberator,the_last_numberator); long the_result_numberator = the_first_numberator/gcd_3*the_last_numberator;
long the_result_denominator = gcd(the_first_denominator,the_last_denominator);
if(the_first_numberator%the_result_denominator!=0)
System.out.println(the_result_numberator+"/"+the_result_denominator);
else
System.out.println(the_result_numberator/the_result_denominator);
}
}
}

思路是从其他博主哪里学习来的,贴上链接:

https://www.cnblogs.com/William-xh/p/7203232.html?utm_source=itdadao&utm_medium=referral

代码已经ac

希望对大家有所帮助

以上

05-11 22:23