Skip to content

Commit 2ee65f7

Browse files
committed
Added Resursive implementation to get nth fibonacci number with memoization
1 parent 7f60d57 commit 2ee65f7

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.thealgorithms.maths;
2+
3+
import java.math.BigInteger;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
/**
8+
* author : @pri-sin
9+
* This class provides methods for calculating Fibonacci numbers Recursion.
10+
*/
11+
public final class FibonacciJavaRecursion {
12+
static Map<Integer, BigInteger> fibonacciMap=new HashMap<>();
13+
14+
private FibonacciJavaRecursion() {
15+
// Private constructor to prevent instantiation of this utility class.
16+
}
17+
18+
/**
19+
* Calculates the nth Fibonacci number.
20+
*
21+
* @param n The index of the Fibonacci number to calculate.
22+
* @return The nth Fibonacci number as a BigInteger.
23+
* @throws IllegalArgumentException if the input 'n' is a negative integer.
24+
*/
25+
public static BigInteger computeRecursively(final int n) {
26+
if (n < 0) {
27+
throw new IllegalArgumentException("Input 'n' must be a non-negative integer.");
28+
}
29+
30+
if (n <= 1) {
31+
fibonacciMap.put(n, BigInteger.valueOf(n));
32+
return BigInteger.valueOf(n);
33+
}
34+
35+
if(!fibonacciMap.containsKey(n)) {
36+
fibonacciMap.put(n, computeRecursively(n-2).add(computeRecursively(n-1)));
37+
}
38+
39+
return fibonacciMap.get(n);
40+
}
41+
42+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.math.BigInteger;
7+
import org.junit.jupiter.api.Test;
8+
9+
public class FibonacciJavaRecursionTest {
10+
@Test
11+
public void checkValueAtZero() {
12+
assertEquals(BigInteger.ZERO, FibonacciJavaRecursion.computeRecursively(0));
13+
}
14+
15+
@Test
16+
public void checkValueAtOne() {
17+
assertEquals(BigInteger.ONE, FibonacciJavaRecursion.computeRecursively(1));
18+
}
19+
20+
@Test
21+
public void checkValueAtTwo() {
22+
assertEquals(BigInteger.ONE, FibonacciJavaRecursion.computeRecursively(2));
23+
}
24+
25+
@Test
26+
public void checkRecurrenceRelation() {
27+
for (int i = 0; i < 100; ++i) {
28+
assertEquals(FibonacciJavaRecursion.computeRecursively(i + 2), FibonacciJavaRecursion.computeRecursively(i + 1).add(FibonacciJavaRecursion.computeRecursively(i)));
29+
}
30+
}
31+
32+
@Test
33+
public void checkNegativeInput() {
34+
assertThrows(IllegalArgumentException.class, () -> { FibonacciJavaRecursion.computeRecursively(-1); });
35+
}
36+
}

0 commit comments

Comments
 (0)