題目描述:
輸入輸出描述:
示例:
題目解析:
(一)投機取巧版
感覺題目本意是想讓答題者用代碼找最小公倍數和最大公約數的。但是根據觀察,當a和b取n和(n-1)的時候,lcm(a,b)-gcd(a,b)的差就是最小的(最小公倍數是兩者乘積,最大公約數是1)。所以代碼如下:
n=input()
n=int(n)
outputresult=n*(n-1)-1
print(outputresult)
但是這樣寫,代碼的通過率是70%。考試結束後有大神po上自己通過率100%的代碼如下:
while True:
try:
n=int(input())
lcm=n*(n-1)
gcd=1
print(lcm-gcd)
except:
break
對此有點百思不得其解。
(二)正統版
學弟寫了一段用代碼找最小公倍數和最大公約數、並用循環找最大差值的代碼。比較符合出題者意圖,自測通過,但是由於時間原因並沒有在系統裏測試。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n =Integer.parseInt( s.nextLine());
int cha = 0;
Test t = new Test();
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if (i!=j) {
int temp = t.lcm(i, j)-t.gcd(i, j);
if (temp>cha) {
cha=temp;
}
}
}
}
System.out.println(cha);
}
public static int gcd(int a,int b){
int n = 0;
while(b!=0){
n = a % b;
a = b;
b = n;
}
return a ;
}
public int lcm(int a,int b) {
return a * b / gcd(a,b);
}
}