Skip to content

Commit 3bb5cfc

Browse files
committed
Daily Coding Problem | Day 849 | Collatz sequence
1 parent 188a1c0 commit 3bb5cfc

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

daily-coding-problem/src/main/java/com/devstromo/day849/Problem.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public class Problem {
44

5-
public int solve(long n) {
5+
public long solve(long n) {
66
var iterations = 0;
77
while (n > 1) {
88
iterations++;
@@ -14,4 +14,14 @@ public int solve(long n) {
1414
}
1515
return iterations;
1616
}
17+
18+
public long solveRecursive(long n) {
19+
if (n == 1) {
20+
return 0;
21+
}
22+
if (n % 2 == 0) {
23+
return solveRecursive(n / 2) + 1;
24+
}
25+
return solveRecursive(3 * n + 1) + 1;
26+
}
1727
}

daily-coding-problem/src/test/java/com/devstromo/day849/ProblemUnitTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,16 @@ public void testSolve(long input, long expected) {
2121
assertEquals(expected, result, "Expected " + expected + " iterations for input " + input);
2222
}
2323

24+
@ParameterizedTest
25+
@CsvSource({
26+
"8, 3",
27+
"3, 7",
28+
"1, 0",
29+
"27, 111"
30+
})
31+
public void testSolveRecursive(long input, long expected) {
32+
final var result = problem.solveRecursive(input);
33+
assertEquals(expected, result, "Expected " + expected + " iterations for input " + input);
34+
}
35+
2436
}

0 commit comments

Comments
 (0)