挑战编程 程序设计竞赛训练手册-1.6.13n+1问题(3n+1 Problem)
代码:
public class problem_3n_add_1 {
/**
* @param args
*/
public static void main(String[] args) {
int i = 900;//初始值
int j = 1000;//最终值
int result = maxCount(i,j);//最大运算次数
System.out.print(i + " " + j + " " + result);//输出结果
}
private static int maxCount(int i, int j) {//循环最小数至最大数,得出最大运算次数
int result ;//声明变量,保存计算结果
int tempcount = 0;//定义临时计数器,记录某一数字的计算次数
for (int x = i; x <= j; x++) {//比较从i到j的每个整数,运用3n+1算法,得到的最大循环节长度
result = x;//初始化运算结果变量,初始值为最小值i-最大值j中循环到的某一数值
int count = 1;//临时数据,记录完成3n+1算法所需的计算次数
do {//3n+1算法
result = judge(result);//把此次结果带人下一次计算
count++;//记录次数+1
} while (result != 1);
if (tempcount < count)//返回最大值
tempcount = count;
}
return tempcount;
}
private static int judge(int j) {//判断奇偶
int result = 0;
if (j % 2 != 0) {
result = j * 3 + 1; //奇数*3+1
} else {
result = j / 2;// 偶数/2
}
return result;
}
}
结果: