0

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.

user1892304
  • 617
  • 1
  • 6
  • 11
  • That code for "pathNumber" is completely broken. It doesn't take into account that the values of the sequence could get larger and larger and overflow. So in the really interesting cases it will not show the right result. – gnasher729 Apr 06 '14 at 13:03
  • 1
    And really there is no need to write code for this because the smallest integer with a path length of n is always 2^n. – gnasher729 Apr 06 '14 at 13:05
  • 2
    @gnasher729 I temporarily changed it from "long" to "int" to see if a data type incompatibility was causing the problem "And really there is no need to write code for this because the smallest integer with a path length of n is always 2^n." Not necessarily. For example firstInstanceOf(14) is 11 as opposed to 2^14. – user1892304 Apr 06 '14 at 14:22

0 Answers0