Skip to content

Commit 4dabd53

Browse files
add power
1 parent 2ed3fc2 commit 4dabd53

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.examplehub.maths;
2+
3+
public class Power {
4+
5+
/**
6+
* Returns the value of the first argument raised to the power of the second argument.
7+
*
8+
* @param a the base.
9+
* @param b the exponent.
10+
* @return the value {@code a}<sup>{@code b}</sup>.
11+
*/
12+
public static long pow(int a, int b) {
13+
int power = 1;
14+
for (int i = 1; i <= b; i++) {
15+
power *= a;
16+
}
17+
return power;
18+
}
19+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.examplehub.maths;
2+
3+
public class PowerRecursion {
4+
5+
/**
6+
* Returns the value of the first argument raised to the power of the second argument using recursion.
7+
*
8+
* @param a the base.
9+
* @param b the exponent.
10+
* @return the value {@code a}<sup>{@code b}</sup>.
11+
*/
12+
public static long pow(int a, int b) {
13+
return b == 0 ? 1 : a * pow(a, b - 1);
14+
}
15+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class PowerRecursionTest {
8+
9+
@Test
10+
void testPow() {
11+
assertEquals(1, PowerRecursion.pow(0, 0));
12+
assertEquals(0, PowerRecursion.pow(0, 10));
13+
assertEquals(1, PowerRecursion.pow(1, 0));
14+
assertEquals(2, PowerRecursion.pow(2, 1));
15+
assertEquals(8, PowerRecursion.pow(2, 3));
16+
assertEquals(1024, PowerRecursion.pow(2, 10));
17+
assertEquals(625, PowerRecursion.pow(25, 2));
18+
}
19+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class PowerTest {
8+
9+
@Test
10+
void testPow() {
11+
assertEquals(1, Power.pow(0, 0));
12+
assertEquals(0, Power.pow(0, 10));
13+
assertEquals(1, Power.pow(1, 0));
14+
assertEquals(2, Power.pow(2, 1));
15+
assertEquals(8, Power.pow(2, 3));
16+
assertEquals(1024, Power.pow(2, 10));
17+
assertEquals(625, Power.pow(25, 2));
18+
}
19+
}

0 commit comments

Comments
 (0)