Add tests for power using recursion algorithm (#4335)
This commit is contained in:
parent
ebd356e182
commit
80a4435038
@ -1,23 +0,0 @@
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
public class PowRecursion {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0;
|
||||
assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0;
|
||||
assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0;
|
||||
assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the second
|
||||
* argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
return b == 0 ? 1 : a * pow(a, b - 1);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
/**
|
||||
* calculate Power using Recursion
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public class PowerUsingRecursion {
|
||||
|
||||
public static double power(double base, int exponent) {
|
||||
// Base case: anything raised to the power of 0 is 1
|
||||
if (exponent == 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Recursive case: base ^ exponent = base * base ^ (exponent - 1)
|
||||
// Recurse with a smaller exponent and multiply with base
|
||||
return base * power(base, exponent - 1);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Test case for Power using Recursion
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
class PowerUsingRecursionTest {
|
||||
|
||||
@Test
|
||||
void testPowerUsingRecursion() {
|
||||
assertEquals(32.0, PowerUsingRecursion.power(2.0, 5));
|
||||
assertEquals(97.65625, PowerUsingRecursion.power(2.5, 5));
|
||||
assertEquals(81, PowerUsingRecursion.power(3, 4));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user