Files
30-seconds-of-code/snippets/collatz.md
Christian Bender c236de3e67 collatz algorithm
collatz algorithm as function
2017-12-13 23:02:42 +01:00

242 B

Collatz algorithm

If n even then returns n/2 otherwise (n is odd) 3n+1. It uses the ternary operator.

    const collatz = n => (n % 2 == 0) ? (n/2) : (3*n+1); 
    // collatz(8) --> 4
    // collatz(5) --> 16