Collat​​z序列问题

Gan*_*row 4 java algorithm

我正在尝试解决这个问题,它不是一个功课问题,它只是我提交给uva.onlinejudge.org的代码,所以我可以通过例子学习更好的java.以下是问题示例输入:

 3 100
 34 100
 75 250
 27 2147483647
 101 304
 101 303
 -1 -1
Run Code Online (Sandbox Code Playgroud)

这是简单的输出:

 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
Run Code Online (Sandbox Code Playgroud)

事情是这样有,否则你的问题将不被接受为解决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;
  }
}
Run Code Online (Sandbox Code Playgroud)

是的,这就是它的意义:

Lothar Collat​​z给出的算法产生整数序列,描述如下:

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. 
Run Code Online (Sandbox Code Playgroud)

是的,我的问题是如何在3秒的时间间隔内使其工作?

Mar*_*ers 5

从谷歌搜索我发现这个线程,其他几个人有同样的问题,解决方案是使用64位算术而不是32位算术.

尝试改变int,以long看看是否有帮助.