Last active
November 5, 2019 08:54
-
-
Save pinglunliao/c18978c18630f3b8cd1b to your computer and use it in GitHub Desktop.
c039: 00100 - The 3n + 1 problem. FYI: https://yunlinsong.blogspot.com/2015/03/c039-00100-3n-1-problem.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int get_cycle_length(int num); | |
int main(void) | |
{ | |
int i, j, k, start, end; | |
int maximum = 1; | |
int cycleLength; | |
while( cin >> i >> j ) | |
{ | |
maximum = 1; | |
start = i; | |
end = j; | |
if( i > j ) // ensure "start" is less than "end" | |
{ | |
start = j; | |
end = i; | |
} | |
for(k = start; k <= end; k++) | |
{ | |
cycleLength = get_cycle_length(k); | |
if(maximum < cycleLength) | |
maximum = cycleLength; | |
} | |
cout << i << " " << j << " " << maximum << endl; | |
} | |
return 0; | |
} | |
int get_cycle_length(int num) | |
{ | |
int cycleLength = 1; | |
while(num != 1) | |
{ | |
num = (num % 2 == 0 ? num / 2: (num*3) + 1); | |
cycleLength++; | |
} | |
return cycleLength; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment