Problem
Übersetzung anzeigenStart 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.
Einschränkungen
1 ≤ n ≤ 10,000. Inputs in this range reach 1 under this rule; all sequence values fit a signed 64-bit integer.
Beispiele
Eingabe:
n = 6
Erwartete Ausgabe:
expected = [6, 3, 10, 5, 16, 8, 4, 2, 1]
Eingabe:
long long n = 6;
Erwartete Ausgabe:
std::vector<long long> expected = {6, 3, 10, 5, 16, 8, 4, 2, 1};
Eingabe:
long n = 6;
Erwartete Ausgabe:
long[] expected = new long[] {6, 3, 10, 5, 16, 8, 4, 2, 1};
Erläuterung
6 is even, so it becomes 3. Then 3 becomes 10. Continue applying the rule until 1.
Eingabe:
n = 1
Erwartete Ausgabe:
expected = [1]
Eingabe:
long long n = 1;
Erwartete Ausgabe:
std::vector<long long> expected = {1};
Eingabe:
long n = 1;
Erwartete Ausgabe:
long[] expected = new long[] {1};
Erläuterung
The starting value is already 1, so no transformations are needed.
Referenzen
Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.