Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/main/java/com/thealgorithms/maths/FibonacciJavaRecursion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.thealgorithms.maths;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
* author : @pri-sin
* This class provides methods for calculating Fibonacci numbers using Recursion with Memoization.
*/
public final class FibonacciJavaRecursion {
static Map<Integer, BigInteger> fibonacciMap=new HashMap<>();

private FibonacciJavaRecursion() {
// Private constructor to prevent instantiation of this utility class.
}

/**
* Calculates the nth Fibonacci number.
*
* @param n The index of the Fibonacci number to calculate.
* @return The nth Fibonacci number as a BigInteger.
* @throws IllegalArgumentException if the input 'n' is a negative integer.
*/
public static BigInteger computeRecursively(final int n) {
if (n < 0) {
throw new IllegalArgumentException("Input 'n' must be a non-negative integer.");
}

if (n <= 1) {
fibonacciMap.put(n, BigInteger.valueOf(n));
return BigInteger.valueOf(n);
}

if(!fibonacciMap.containsKey(n)) {
fibonacciMap.put(n, computeRecursively(n-2).add(computeRecursively(n-1)));
}

return fibonacciMap.get(n);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.thealgorithms.maths;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.math.BigInteger;
import org.junit.jupiter.api.Test;

public class FibonacciJavaRecursionTest {
@Test
public void checkValueAtZero() {
assertEquals(BigInteger.ZERO, FibonacciJavaRecursion.computeRecursively(0));
}

@Test
public void checkValueAtOne() {
assertEquals(BigInteger.ONE, FibonacciJavaRecursion.computeRecursively(1));
}

@Test
public void checkValueAtTwo() {
assertEquals(BigInteger.ONE, FibonacciJavaRecursion.computeRecursively(2));
}

@Test
public void checkRecurrenceRelation() {
for (int i = 0; i < 100; ++i) {
assertEquals(FibonacciJavaRecursion.computeRecursively(i + 2), FibonacciJavaRecursion.computeRecursively(i + 1).add(FibonacciJavaRecursion.computeRecursively(i)));
}
}

@Test
public void checkNegativeInput() {
assertThrows(IllegalArgumentException.class, () -> { FibonacciJavaRecursion.computeRecursively(-1); });
}
}
Loading