Using C++, I was writing a program that would take the first n numbers starting at 1 and output their respective "path count", which is what I call the number of iterations of the Collatz sequence it takes to get from the number to zero (see the Wikipedia article on the Collatz Conjecture). For example, the path number of 8 is 3, because it takes to 3 steps to get to 1 (8 : 2 = 4; 4 : 2 = 2; 2 : 2 = 1).
Thus we have the simple function:
int pathNumber(int n){
int pathCount = 0;
while(n > 1){
if(n % 2 == 0){
n /= 2;
}else{
n *= 3;
n ++;
}
pathCount ++;
}
return pathCount;
}
I then decided to write an inverse function of this (called firstInstanceOf(n)), which would compute the first instance of any given pathNumber in ascending order from 1. For example, firstInstanceOf(3) would be 8, because 8 is the first number in ascending order from 1 whose pathCount is 3. The function I wrote is as follows:
int firstInstanceOf(int s){
int i = 0;
while(pathNumber(i) != s){
i ++;
}
return i;
}
where s is the input value and i is the variable that increments by 1 each time. As simple as it seems, the code compiles without any warnings but simply will not compute. I have tried reformatting the latter function as a for loop, as an infinity loop, etc. but still the program persists in either buffering indefinitely or outputting bogus values. I feel like I am missing something very obvious? Any help appreciated.