r/programmingrequests • • Oct 17 '22

Solved✔️ A simple math calculation problem in C++

I usually code in Python, but I need to solve this problem faster by using C++ (or any other language that may be faster for this case).

The task is about the Collatz conjecture. Take any number N. If it is odd, multiply by 3 and add 1 (N -> 3N+1), if it is even, divide by two (N -> N/2). Repeat until it gets to one.

Example with number 3: 3, 10, 5, 16, 8, 4, 2, 1

Let Col(N) be a function that outputs the number of steps in this process. For the example above, Col(3) = 7

Then, the program needs to output the sum of Col(k) from k=1 to m, for some input number m, that is, to return Col(1) + Col(2) + Col(3) + ... + Col(m)

The Wikipedia article on the Collatz conjecture has a description on the computation in binary, if it is of any use.

2 Upvotes

9 comments sorted by

View all comments

1

u/thedgyalt Oct 18 '22 edited Oct 18 '22

This is meant to be solved recursively.

#include <iostream>

int coll(int n, int steps);

int main(void) 
{
    int M = 0;

    std::cout << "Enter a number: \n";
    std::cin >> M;

    int result = 0;

    for (int n = 1; n <= M; n++)
    {
        result += coll(n, 0);
    }

    std::cout << "The sum of collatz conjecture results up to M is: " << result << std::endl;

    return 0;
}

int coll(int n, int steps)
{
    if (n == 1)
    {
        return steps;
    }

    if (n % 2 != 0)
    {
        return coll((n*3)+1, ++steps);
    }
    return coll(n/2, ++steps);

}