Skip to content

Latest commit

 

History

History
64 lines (45 loc) · 1.41 KB

collatz.md

File metadata and controls

64 lines (45 loc) · 1.41 KB

Collatz 6 Kyu

LINK TO THE KATA - NUMBER THEORY ALGORITHMS

Description

Preface

A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 :

$$ f(n) = \begin{cases} n/2 & \text{if } n \text{ is even} \\ 3n+1 & \text{if } n \text{ is odd} \\ \end{cases} $$


A more detailed description of the collatz conjecture may be found on Wikipedia.

The Problem

Create a function collatz that returns a collatz sequence string starting with the positive integer argument passed into the function, in the following form:

"X0->X1->...->XN"

Where Xi is each iteration of the sequence and N is the length of the sequence.

Sample Input

Input: 4
Output: "4->2->1"

Input: 3
Output: "3->10->5->16->8->4->2->1"

Don't worry about invalid input. Arguments passed into the function are guaranteed to be valid integers >= 1.

Solution

const collatz = n => {
  const sequence = [n]

  while (n !== 1) {
    if (n % 2 === 0) {
      n = n / 2
    } else {
      n = n * 3 + 1
    }
    sequence.push(n)
  }

  return sequence.join('->')
}