forked from mahmudahsan/203-ACM-Problems-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
694.cpp
executable file
·67 lines (56 loc) · 1.62 KB
/
694.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Problem: The Collatz Sequence UVa 694
Programmer: Md. Mahmud Ahsan
Compiled: Linux GNU C++
Date: 05-08-04
*/
/*********************************************************************
We have to follow the 3n + 1 law for the initial value a's input. if a == 1 break
By computing Step 4, if a > l (limit value) then break without counting length of sequence
We have to use do - while loop
***********************************************************************/
#include <iostream>
using namespace std;
// typedef
typedef long long int llint;
// prototypes
llint cycle(llint, llint);
void show(int, llint, llint, llint);
//====================================================================
int main(){
llint a, l, temp, max; // a means first input and l means last input
static int count = 0;
while (cin >> a >> l){
if (a < 0 && l < 0) break;
// always keep a to lower value
if (a > l){
temp = a;
a = l;
l = temp;
}
max = cycle(a, l);
++count;
// print the desired output
show(count, a, l, max);
}
return 0;
}
//====================================================================
llint cycle(llint a, llint l){ // a means first input, l means last input
int i = 1;
do{
// applying 3n + 1 law with modification
if (a % 2 == 0){
a = a / 2;
++i;
}
else{
a = 3 * a + 1;
if (a > l) break; // if a > l not count the sequence
++i;
}
}while (a != 1);
return i;
}
void show(int i, llint a, llint l, llint max){
cout << "Case " << i << ": A = " << a << ", limit = " << l << ", number of terms = " << max << endl;
}