Retour aux défis
Facile 0 résolus 0 % de réussite

Collatz Sequence

Follow the halve-or-triple-and-add-one rule until reaching 1.

Ce que vous allez apprendre

  • Follow a rule until a condition is met
  • Count the steps taken
  • Branch on even and odd values

Problème

Afficher la traduction

Start with n. If it is even, divide it by 2; if it is odd, multiply it by 3 and add 1. Repeat until the value is 1. Include both the starting value and the final 1 in your answer.

Implement collatz_sequence(n).

Input

n: The positive starting integer.

Output

Return the complete sequence in order.

Contraintes

1 ≤ n ≤ 10,000. Inputs in this range reach 1 under this rule; all sequence values fit a signed 64-bit integer.

Exemples

Exemple 1
Entrée :
n = 6

Sortie attendue :
expected = [6, 3, 10, 5, 16, 8, 4, 2, 1]
Entrée :
long long n = 6;

Sortie attendue :
std::vector<long long> expected = {6, 3, 10, 5, 16, 8, 4, 2, 1};
Entrée :
long n = 6;

Sortie attendue :
long[] expected = new long[] {6, 3, 10, 5, 16, 8, 4, 2, 1};

Explication

6 is even, so it becomes 3. Then 3 becomes 10. Continue applying the rule until 1.

Exemple 2
Entrée :
n = 1

Sortie attendue :
expected = [1]
Entrée :
long long n = 1;

Sortie attendue :
std::vector<long long> expected = {1};
Entrée :
long n = 1;

Sortie attendue :
long[] expected = new long[] {1};

Explication

The starting value is already 1, so no transformations are needed.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

The sequence is generated by repeatedly applying one rule based on whether the current number is even or odd.

Indice 2

Keep appending each new value until you reach 1.

Indice 3

Watch out that the starting value itself and the final 1 must both appear in the result.

Complexité attendue

O(k) time, O(k) extra space, where k is the sequence length

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.