Conjecture: For any natural number greater than 1 N, if n is odd, then n becomes 3n+1, otherwise it becomes half of N.
After a number of such transformations, the n will be changed to 1. such as 3->10->5->16->8->2->1.
Enter N, the number of times the transformation is output. N≤10^9.
Example input: 3
Sample output: 7
Write the following code without hesitation:
#include <stdio.h>int main (void) {int n;int count=0;scanf ("%d", &n), while (n > 1) {if (n%2! = 0) n = 3*n + 1;elsen /= 2;count++;} printf ("%d\n", count); return 0;}
However, is the procedure correct? Unfortunately, if you enter 987654321, the answer is 1, which is obviously wrong. by debugging or printing the value of n in the loop body with a printf statement, you see that the value of n is negative, causing the program to exit after a single loop. From here we can learn that the value of n overflows because the integer maximum value is 2^31-1 = 2147483647, approximately 2.1 billion, and the maximum value of test instructions n is 1 billion (10^9), so it is dangerous to multiply the value of N by 3, which can cause overflow.
The solution is as follows:
Because odd * odd = odd, so after n=3*n+1 calculation, the value of n is necessarily an even number, and the next cycle must do the operation n/=2, so here can merge these two steps, that is, n is an odd case to do the operation N=floor (1.5*n+0.5), Because of the error problem of double value, we can use N=floor (1.5*n+1) (floor function to receive a double type parameter, return the maximum number of shapes not greater than the given parameter, the return value type is double), Assigns the integer double value to shaping to discard the decimal point.
The modified program is as follows:
#include <stdio.h> #include <math.h>int main (void) {int n;int count=0;scanf ("%d", &n), while (n > 1) {if (n%2! = 0) { n = floor (1.5*n + 1); Count + = 2; } else{ n = n/2; count++;}} printf ("%d\n", count); return 0;}
Test again with 987654321 to get the result 180 times. Furthermore, if the limit for n is the scope of the shaping int, the program cannot complete the request, then we can use a long long int.
Reference: "Algorithmic Competition Primer Classic"--Rujia
Finally some doubts (see the Master can answer one or two, I will be greatly appreciated):
1, here is the second program I wrote according to the author's tips, I think it should be correct:-), but there are some doubts, such as we consider the first n input value, but the loop
The second time, the third ... How do we explain that the value of the loop will not overflow in the future?
For example, when the value of n at the beginning is 7, then the value of the loop is 11, and 11>7. This means that the value of the two cycles is greater than 7.
2, moreover, how do we know that after a number of transformations will be 1, that is to say how we know the function convergence? Well... It seems to be a mathematical problem.
3n+1 problems