diff --git a/src/main/java/com/thealgorithms/maths/FibonacciWithDP.java b/src/main/java/com/thealgorithms/maths/FibonacciWithDP.java new file mode 100644 index 000000000000..b5fc5d470688 --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/FibonacciWithDP.java @@ -0,0 +1,40 @@ +package com.thealgorithms.maths; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * author : @pri-sin + * This class provides methods for calculating Fibonacci numbers using Recursion with Memoization. + */ +public final class FibonacciWithDP { + static List fibonacciList=new ArrayList<>(Arrays.asList(BigInteger.ZERO,BigInteger.ONE)); + + private FibonacciWithDP() { + } + + /** + * 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) { + return fibonacciList.get(n); + } + + if(fibonacciList.size()<=n) { + fibonacciList.add(computeRecursively(n-2).add(computeRecursively(n-1))); + } + + return fibonacciList.get(n); + } +} diff --git a/src/test/java/com/thealgorithms/maths/FibonacciWithDPTest.java b/src/test/java/com/thealgorithms/maths/FibonacciWithDPTest.java new file mode 100644 index 000000000000..ed2a8864f8b7 --- /dev/null +++ b/src/test/java/com/thealgorithms/maths/FibonacciWithDPTest.java @@ -0,0 +1,34 @@ +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; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class FibonacciWithDPTest { + @Test + public void checkValueAtZero() { + assertEquals(BigInteger.ZERO, FibonacciWithDP.computeRecursively(0)); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + public void checkValueAtOneAndTwo(int number) { + assertEquals(BigInteger.ONE, FibonacciWithDP.computeRecursively(number)); + } + + @Test + public void checkRecurrenceRelation() { + for (int i = 0; i < 100; ++i) { + assertEquals(FibonacciWithDP.computeRecursively(i + 2), FibonacciWithDP.computeRecursively(i + 1).add(FibonacciWithDP.computeRecursively(i))); + } + } + + @Test + public void checkNegativeInput() { + assertThrows(IllegalArgumentException.class, () -> { FibonacciWithDP.computeRecursively(-1); }); + } +}