我正在嘗試在 HackerEarth中解決這個練習。但我有一個超出時間限制的錯誤。這是我寫的代碼:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
//gcd
public static long gcd(long num1, long num2) {
if (num2 != 0) {
return gcd(num2, num1 % num2);
} else {
return num1;
}
}
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine()); // Reading input from STDIN
while (T-- > 0) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
long a = Long.parseLong(st1.nextToken());
long b = Long.parseLong(st1.nextToken());
long A = a/gcd(a,b);
long B = b/gcd(a,b);
System.out.printf("%d%1s%d%n",B,"",A);
}
}
}
uj5u.com熱心網友回復:
由于實施不當,您的解決方案有點慢。我用與您的解決方案相同的邏輯和時間復雜度以更好的實施方式重寫了您的解決方案并被接受,并且沒有一個測驗用例超過0.8 秒
import java.util.*;
class TestClass {
// Same gcd function but it's better code :)
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int t = s.nextInt(); // this way of reading input is faster alot.
while(t-- > 0) {
int a = s.nextInt();
int b = s.nextInt(); // No need to use long it's just 1e9
int tmp = gcd(a, b); // It's better to save the value of the gcd(a, b) instead of calculate it twice.
int A = a/tmp;
int B = b/tmp;
System.out.println(B " " A);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478410.html
上一篇:如何在python中詢問20個數字,然后列印正數和負數的總和?
下一篇:C 中的斐波那契數溢位
