我試圖解決這個問題,它不是一個家庭作業問題,它只是我提交給uva.onlinejudge.org的代碼,所以我可以更好地學習java trough的例子。這裏的問題是樣本輸入:Collatz序列問題
3 100
34 100
75 250
27 2147483647
101 304
101 303
-1 -1
下面是簡單的輸出:
Case 1: A = 3, limit = 100, number of terms = 8
Case 2: A = 34, limit = 100, number of terms = 14
Case 3: A = 75, limit = 250, number of terms = 3
Case 4: A = 27, limit = 2147483647, number of terms = 112
Case 5: A = 101, limit = 304, number of terms = 26
Case 6: A = 101, limit = 303, number of terms = 1
事情是這樣有,否則你的問題將不被接受爲解決3秒的時間間隔內執行,這裏是什麼我已經出來,到目前爲止,它的工作,因爲它應該只是執行時間沒有在3秒鐘內,這裏是代碼:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int start;
int limit;
int terms;
int a = 0;
while (stdin.hasNext()) {
start = stdin.nextInt();
limit = stdin.nextInt();
if (start > 0) {
terms = getLength(start, limit);
a++;
} else {
break;
}
System.out.println("Case "+a+": A = "+start+", limit = "+limit+", number of terms = "+terms);
}
}
public static int getLength(int x, int y) {
int length = 1;
while (x != 1) {
if (x <= y) {
if (x % 2 == 0) {
x = x/2;
length++;
}else{
x = x * 3 + 1;
length++;
}
} else {
length--;
break;
}
}
return length;
}
}
是的這裏是它的意思如何解決:
通過洛塔爾·科拉茨給出的算法生成一個整數序列,並說明如下:
Step 1:
Choose an arbitrary positive integer A as the first item in the sequence.
Step 2:
If A = 1 then stop.
Step 3:
If A is even, then replace A by A/2 and go to step 2.
Step 4:
If A is odd, then replace A by 3 * A + 1 and go to step 2.
是的,我的問題是我怎樣才能使它時間爲3秒的時間間隔內工作?
而你的問題是? – 2010-04-05 13:29:42
這裏有一個Java條目:http://stackoverflow.com/questions/2388254/code-golf-collatz-conjecture;) – kennytm 2010-04-05 13:30:54
@KennyTM條目有不同的方式,我的工作只是基準違反(3秒) – 2010-04-05 13:33:28