Challenge programming Programming Competition Training Manual-1.6.13N + 1 problem(3N + 1 problem)
Code:
Public class problem_3n_add_1 {/*** @ Param ARGs */public static void main (string [] ARGs) {int I = 900; // The initial value is Int J = 1000; // final value int result = maxcount (I, j); // maximum number of operations system. out. print (I + "" + J + "" + result); // output result} Private Static int maxcount (int I, Int J) {// the minimum number of cycles to the maximum number of operations to obtain the maximum number of operations int result; // declare the variable and save the calculation result int tempcount = 0; // define a temporary counter, record the number of computations of a number for (INT x = I; x <= J; X ++) {// compare each integer from I to J, use the 3N + 1 algorithm to obtain the maximum cyclic section. Result = x; // initialize the calculation result variable. The initial value is int COUNT = 1, which is returned by a loop in the smallest I-maximum J. // temporary data, record the number of computations required to complete the 3N + 1 algorithm do {// 3N + 1 algorithm result = judge (result); // This result is taken to count ++ for the next computation; // record count + 1} while (result! = 1); If (tempcount <count) // returns the maximum value tempcount = count;} return tempcount;} Private Static int judge (Int J) {// judge the parity int result = 0; If (J % 2! = 0) {result = J * 3 + 1; // odd number * 3 + 1} else {result = J/2; // even number/2} return result ;}}
Result: