6 kyu

Basic Optimization - Collatz Sum Sequence

Description:

The Collatz Conjecture

I'm pretty sure you know about this famous conjecture already. Given this recursively defined function

f(n)={n2,if n0(mod2)3n+1,if n1(mod2) f(n) = \begin{cases} \frac{n}{2}, & \text{if } n \equiv 0 \pmod{2} \\ 3n + 1, & \text{if } n \equiv 1 \pmod{2} \end{cases}

the task is to decide whether or not a given starting number will ever reach one if f is iterated enough. These iterations give us a sequence with a certain length that ends when one is finally reached:

10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

when starting with 10, the length of the sequence is 6 
(the one is excluded)

The conjecture says that every natural number will eventually reach one, but whether or not this is true is an open question. We will assume it is true for the purposes of this kata.

A simple sum sequence

Let's define a sequence using the previous function!

Given a number n, we define l(n) as the length of the sequence given by the iteration of the collatz function above. Then, we define collatz_sum(n) as the sum of all l(i) for all i in the range [1, n].

Your task is to define the collatz_sum function and to make it as fast as possible.

Technical notes

The validation function takes approximately 5 seconds to execute in order to force your solution to be approximately as fast as mine (which is not very hard).

All the inputs are in the range [1, 2*10^6]. The exact test ranges are given when the tests are executed. Most tests are random.

Algorithms

More By Author:

Check out these other kata created by Dr Gabo

Stats:

CreatedFeb 13, 2020
PublishedFeb 13, 2020
Warriors Trained288
Total Skips85
Total Code Submissions242
Total Times Completed43
Python Completions43
Total Stars9
% of votes with a positive feedback rating85% of 24
Total "Very Satisfied" Votes18
Total "Somewhat Satisfied" Votes5
Total "Not Satisfied" Votes1
Total Rank Assessments19
Average Assessed Rank
6 kyu
Highest Assessed Rank
4 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • Dr Gabo Avatar
  • dfhwze Avatar
  • saudiGuy Avatar
Ad