This is an easy problem from uva judge http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=36
Brute Force, Iterative, Complete search.
How I did it
- I read i and j.
- I save the values of i and j in oi = i and oj =j. (Just for the output).
- If i is greater than j swap i and j.
- Traverse i to j and calculate the cycle length of the current number.
- Save the max length cycle.
- Print oi, oj and the max length cycle.
- Accepted! 😀
Hints
- j can be greater than i.
- Print i and j in the original order. Print j i will give us wrong answer.
Code
#include <bits/stdc++.h> using namespace std; int getCycle(int n) { int cont = 1; while(n != 1) { if(n%2 != 0) n = n*3 + 1; else n/=2; cont++; } return cont; } int main() { int i,j, cycleL, ans; int io, jo; while(scanf("%d %d", &i, &j) != EOF) { io = i, jo = j; if(i > j) swap(i,j); ans = -1000; for(int x=i; x<=j; x++) { cycleL = getCycle(x); ans = max(cycleL, ans); } printf("%d %d %d\n", io, jo, ans); } return 0; }