- 问题 1095: The 3n + 1 problem
考虑下面的算法生成一个数字序列。先从一个整数n。如果n是偶数,除以2,如果n是奇数,乘以3,并添加1。重复此过程,直到n = 1。例如,将对于n生成数的下列序列
n= 22:22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1据推测(但尚未证实),该算法将对于每个整数n在n = 1终止。另外,在上述的例子中,22中的周期长度是16.给出任意两个数字i和j,确定i和j之间在所有数字的最大周期长度(包括两个端点)。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int start,end;
int maxcount = 0;
int a = sc.nextInt();
int b= sc.nextInt();
if(a>b) {
end=a;
start=b;
}else {
start=a;
end=b;
}
for (int i = start; i <= end; i++) {
int count = 1;
int j = i;
while (j != 1) {
if (j % 2 == 0) {
j /= 2;
count++;
} else {
j = j * 3 + 1;
count++;
}
}
if (count > maxcount)
maxcount = count;