The 3n + 1 problem
Problem Descriptionproblems in computer science is often classified as belonging to a certain class of problems (e.g., NP , unsolvable, Recursive). In this problem you'll be analyzing a property of an algorithm whose classification are not known for all possible inputs .
Consider the following algorithm:
1. Input n
2. Print N
3. If n = 1 then STOP
4. If n is odd then n <-3n + 1
5. else N <-N/2
6. GOTO 2
Given the input, the following sequence of numbers would be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above would terminate (when a 1 was printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such 0 < n < 1,000,000 (and, in fact, for many more numbers T Han this.)
Given an input n, it's possible to determine the number of numbers printed (including the 1). For a given n called the cycle-length of N. The example above, the cycle length of is 16.
For any of the numbers I and j you is to determine the maximum cycle length through all numbers between I and J.
Inputthe input would consist of a series of pairs of integers I and J, one pair of integers per line. All integers'll is less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length to all integers between an D including I and J.
You can assume that no opperation overflows a 32-bit integer.
Outputfor each pair of input integers I and j-should output I, j, and the maximum cycle length for integers between an D including I and J. These three numbers should be separated by at least one space with all three numbers on one line and with one line of OUTP UT for each line of input. The integers I and J must appear in the output of the same order in which they appeared in the input and should is Followe D by the maximum cycle length (on the same line).
Sample Input
1 10100 200201) 210900 1000
Sample Output
1 10 20100 200 125201 210 89900 1000 174
You can do what you want to do. Estimate the data is weak, otherwise the direct do should time out (originally wanted to write optimization again, did not expect this problem data is so weak ... )。 The code is as follows:
#include <cstdio>int main () { int n,m; while (scanf ("%d%d", &n,&m) ==2) { int maxn=n>m?n:m;//don't say N and m size, pit Ah! int minx=n>m?m:n; int maxx=0; for (int i=minx;i<=maxn;i++) {//Total feeling this will time out, it seems that the data is not strong AH int x=i,sum=1; while (x!=1) { if (x%2==0) x/=2; else x=3*x+1; sum++; } if (Sum>maxx) maxx=sum; } printf ("%d%d%d\n", N,m,maxx); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 1032.The 3n + 1 problem "attention to detail" "estimated data not strong" "August 21"