Skip to content

Commit 87d6083

Browse files
authored
Add tests for EulersFunction (TheAlgorithms#4216)
1 parent e29a227 commit 87d6083

File tree

2 files changed

+56
-13
lines changed

2 files changed

+56
-13
lines changed
Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
package com.thealgorithms.others;
22

33
/**
4-
* You can read more about Euler's totient function
5-
*
6-
* <p>
7-
* See https://en.wikipedia.org/wiki/Euler%27s_totient_function
4+
* @brief utility class for <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function">Euler's totient function</a>
85
*/
9-
public class EulersFunction {
6+
final public class EulersFunction {
7+
private EulersFunction() {
8+
}
109

11-
// This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time
12-
// complexity;
10+
private static void checkInput(int n) {
11+
if (n <= 0) {
12+
throw new IllegalArgumentException("n must be positive.");
13+
}
14+
}
1315

16+
/**
17+
* @brief computes the value of Euler's totient function for given input
18+
* @details has time complexity of O(sqrt(n))
19+
* @param n the input
20+
* @exception IllegalArgumentException n is non-positive
21+
* @return the value of Euler's totient function for the input
22+
*/
1423
public static int getEuler(int n) {
24+
checkInput(n);
1525
int result = n;
1626
for (int i = 2; i * i <= n; i++) {
1727
if (n % i == 0) {
@@ -26,10 +36,4 @@ public static int getEuler(int n) {
2636
}
2737
return result;
2838
}
29-
30-
public static void main(String[] args) {
31-
for (int i = 1; i < 100; i++) {
32-
System.out.println(getEuler(i));
33-
}
34-
}
3539
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.others;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.HashMap;
7+
import org.junit.jupiter.api.Test;
8+
9+
class EulersFunctionTest {
10+
@Test
11+
public void testGetEuler() {
12+
HashMap<Integer, Integer> testCases = new HashMap<>();
13+
testCases.put(1, 1);
14+
testCases.put(2, 1);
15+
testCases.put(3, 2);
16+
testCases.put(4, 2);
17+
testCases.put(5, 4);
18+
testCases.put(6, 2);
19+
testCases.put(10, 4);
20+
testCases.put(21, 12);
21+
testCases.put(69, 44);
22+
testCases.put(47, 46);
23+
testCases.put(46, 22);
24+
testCases.put(55, 40);
25+
testCases.put(34, 16);
26+
testCases.put(20, 8);
27+
testCases.put(20, 8);
28+
testCases.put(1024, 512);
29+
30+
for (final var tc : testCases.entrySet()) {
31+
assertEquals(tc.getValue(), EulersFunction.getEuler(tc.getKey()));
32+
}
33+
}
34+
35+
@Test
36+
public void testGetEulerThrowsExceptionForNonPositiveInput() {
37+
assertThrows(IllegalArgumentException.class, () -> EulersFunction.getEuler(0));
38+
}
39+
}

0 commit comments

Comments
 (0)