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 <= x < 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 <iostream>
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 < 1000000) {
if (input % 2 == 0)
temp = doEven(input);
else
temp = doOdd(input);
counter = 1;
if (temp > chainLength) {
chainLength = temp;
theBestInput = input;
input++;
return longestChain(input);
} else {
input++;
return longestChain(input);
}
} else {
return theBestInput;
}
}
void printResult() {
std::cout << "LONGEST SEQUENCE: " << longestChain(2) << 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;
}