挑战编程 程序设计竞赛训练手册-1.6.1 3n+1问题(3n+1 Problem)

来源:互联网 发布:国内小众服装品牌知乎 编辑:程序博客网 时间:2024/05/29 11:03

挑战编程 程序设计竞赛训练手册-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;}}

结果:

原创粉丝点击