为了好玩,我正在做一些 ICPC 编程问题,这是 Collatz。我得到了一个正确符合预期输出的输出。但是当涉及到 -1 -1 输入时,我一直无法让程序根据需要结束。
样本输入
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
Java 代码
import java.util.Scanner;
import java.lang.Integer;
public class Collatz {
private static int caseNumber = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
caseNumber++;
int a = in.nextInt();
Integer limit = in.nextInt();
if(a == -1 && limit == -1)
break;
int numberOfTerms = 0;
for(Integer value = a; value != 1; numberOfTerms++){
if(value%2 == 0){
value /= 2;
}else{
value = 3 * value + 1;
}
if(limit < value)
break;
}
numberOfTerms +=1;
System.out.println("Case " + caseNumber + ": A = " + a + ", limit = "
+ limit + ", number of terms = " + numberOfTerms);
System.out.println();
}
}
}