Java Collatz序列问题
我试图解决这个问题,这不是一个家庭作业问题,只是我提交给uva.onlinejudge.org的代码,这样我就可以通过示例学习更好的java。以下是问题示例输入:Java Collatz序列问题,java,algorithm,Java,Algorithm,我试图解决这个问题,这不是一个家庭作业问题,只是我提交给uva.onlinejudge.org的代码,这样我就可以通过示例学习更好的java。以下是问题示例输入: 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
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;
}
}
是的,我的问题是如何让它在3秒的时间间隔内工作?通过谷歌搜索,我发现其他一些人也有同样的问题,解决方法是使用64位算术而不是32位算术
尝试将
int
更改为long
,看看这是否有帮助。这里有一个Java条目:;)@KennyTM入口有很多不同,我的正在工作,只是基准测试被突破了(3秒)3秒在什么平台上?代码执行中很少有东西是用绝对时间值来指定的。@David Thornley它没有说当您提交解决方案时,只是JAVA 1.6.0-JAVA Sun JDK
,它在不到一秒钟的时间内运行localy@Mark拜尔斯,我不知道这有什么不同,运行时间是0.968秒。。差别很大。谢谢区别在于你可能会遇到无限循环,因为你溢出了int。@Larry你能解释一下你的意思吗我不明白,我不认为我运行无限循环是因为while(stdin.hasNext())
当输入用完时应该停止
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.