Back to Comprehensive Rust

Exercise: Collatz Sequence

src/control-flow-basics/exercise.md

latest1.1 KB
Original Source
<!-- Copyright 2023 Google LLC SPDX-License-Identifier: CC-BY-4.0 -->

Exercise: Collatz Sequence

The Collatz Sequence is defined as follows, for an arbitrary n<sub>1</sub> greater than zero:

  • If n<sub>i</sub> is 1, then the sequence terminates at n<sub>i</sub>.
  • If n<sub>i</sub> is even, then n<sub>i+1</sub> = n<sub>i</sub> / 2.
  • If n<sub>i</sub> is odd, then n<sub>i+1</sub> = 3 * n<sub>i</sub> + 1.

For example, beginning with n<sub>1</sub> = 3:

  • 3 is odd, so n<sub>2</sub> = 3 * 3 + 1 = 10;
  • 10 is even, so n<sub>3</sub> = 10 / 2 = 5;
  • 5 is odd, so n<sub>4</sub> = 3 * 5 + 1 = 16;
  • 16 is even, so n<sub>5</sub> = 16 / 2 = 8;
  • 8 is even, so n<sub>6</sub> = 8 / 2 = 4;
  • 4 is even, so n<sub>7</sub> = 4 / 2 = 2;
  • 2 is even, so n<sub>8</sub> = 1; and
  • the sequence terminates.

Write a function to calculate the length of the Collatz sequence for a given initial n.

rust,editable,should_panic
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
{{#include exercise.rs:collatz_length}}
  todo!("Implement this")
}

{{#include exercise.rs:main}}