Project Euler: Longest Collatz Sequence The Collatz Sequence is an iterative sequence that is defined for all positive integers as such:

n → n/2 (n is even)

n → 3n + 1 (n is odd)

If 13 were to be entered into this sequence, the result would be as follows:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

And the total number of terms in the chain would be 10. The sequence always ends with 1.

You must create a program that will calculate for a value in the range of 2 &lt;= x &lt; 1000000. This value must give the longest chain of terms when inputted into the Collatz Sequence.

I will now post my solution. Any criticism would be greatly appreciated. Did I use too many if/else statements? Was recursion not the best thing to use? Anything you have to say.

File Main.cpp

#include "Main.h"
#include &lt;iostream&gt;

  namespace coll {
    int counter(1);

    long long doEven(long long numb) {
      if (numb != 1) {
        if (numb % 2 == 0) {
          counter++;
          return doEven(numb / 2);
        } else
          return doOdd(numb);
      } else
        return counter;
    }

    long long doOdd(long long numb) {
      if (numb != 1) {
        if (numb % 2 != 0) {
          counter++;
          return doOdd((3 * numb) + 1);
        } else
          return doEven(numb);
      } else
        return counter;
    }

    int chainLength(0);
    int temp(0);
    int theBestInput(0);

    int longestChain(int input) {
      if (input &lt; 1000000) {
        if (input % 2 == 0)
          temp = doEven(input);
        else
          temp = doOdd(input);
        counter = 1;
        if (temp &gt; chainLength) {
          chainLength = temp;
          theBestInput = input;
          input++;
          return longestChain(input);
        } else {
          input++;
          return longestChain(input);
        }
      } else {
        return theBestInput;
      }
    }

    void printResult() {
      std::cout &lt;&lt; "LONGEST SEQUENCE: " &lt;&lt; longestChain(2) &lt;&lt; std::endl;
    }
  }


File Main.h

#pragma once
namespace coll {
  extern int counter;
  extern int theBestInput;
  extern int chainLength;
  extern int temp;
  long long doEven(long long numb);
  long long doOdd(long long numb);
  int longestChain(int input);
  void printResult();
}


File Test.cpp

#include "Main.h"
int main() {
  coll::printResult();
  return 0;
}
I think that you are writing similar functions to make very similar things. You can take advantage of ternary operator ? and make a simpler function instead:

int Collatz( int &amp;len, int number )
{
    std::cout &lt;&lt; number &lt;&lt; " - ";
    len++;

    if( number == 1 )
        return 1;

    int NextNumber = number % 2 ? number*3+1 : number/2;

    return Collatz( len, NextNumber );
}


int main()
{
    int len = 0;
    Collatz( len, 13);

    std::cout &lt;&lt; "Lenght: " &lt;&lt; len &lt;&lt; std::endl;

    return 0;
}


The output is:

13 - 40 - 20 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - Lenght: 10