694-the Collatz Sequence
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem &problem=635
An algorithm given by Lothar Collatz produces sequences of integers, and is described as follows:
-
Step 1:
-
Choose an arbitrary positive integer
A as the "the" in the sequence.
-
Step 2:
-
If
A = 1 then stop.
-
Step 3:
-
If
A is even, then replace
a by
a /2 and go to step 2.
-
Step 4:
-
If
A is odd, then replace
A with 3 *
a + 1 and go to step 2.
It has been shown that this algorithm would always stop (in step 2) for initial values of A as large as 9 1, but some values of A encountered in the sequence could exceed the size of an integer on many computers. In this problem we want to determine the length of the sequence which includes all values produced until either the Algorit HM stops (in step 2), or a value larger than some specified limit is would (in step 4).
Input
The input for this problem consists of the multiple test cases. For each case, the ' input contains a single ' with two positive integers, the ' a ' giving value of a (for S TEP 1) and the second giving L, the limiting value for terms in the sequence. Neither of these, A or L, are larger than 2,147,483,647 (the largest value, can be stored in A 32-bit integer). The initial value of A is always less than L. A line which contains two negative integers follows the last case.
Output
For each of the input case display "Case number" (sequentially numbered starting with 1), a colon, the initial value for a, the Limiting value L, and the number of terms computed.
Sample Input
3
2147483647
-1-1-304 303
Sample Output
Case 1: A = 3, limit = +, number of terms = 8 Case
2: a = limit = +, number of terms = case
3: a = 75, Limit = Terms = 3 Case
4:a = +, limit = 2147483647, number of terms = 112 case
5:a =, lim it = 304, number of terms = case
6:a = limit = 303, number of terms = 1
Complete code:
/*0.028s*/
#include <cstdio>
int main (void)
{
int cases = 0, step;
Long Long A, AA, Lim, temp;
while (true)
{
scanf ("%lld%lld", &a, &lim);
if (A < 0) break;
AA = A, step = 1;
while (A!= 1)
{
temp = 3 * A + 1;
if ((A & 1) = = 0) A >>= 1;
else if (temp > Lim) break;
else A = temp;
step++;
}
printf ("Case%d:a =%lld, limit =%lld, number of terms =%d\n", ++cases, AA, Lim, Step);
}
return 0;
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/