Skip to content

Commit 06aaa58

Browse files
EvenCheck
1 parent 4c8a4f2 commit 06aaa58

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.examplehub.maths;
2+
3+
public class EvenCheck {
4+
5+
/**
6+
* Check if a number is even or not using modulus operator.
7+
*
8+
* @param number the number to be checked.
9+
* @return {@code true} if the given number is even, otherwise {@code false}.
10+
*/
11+
public static boolean isEven(int number) {
12+
return number % 2 == 0;
13+
}
14+
15+
/**
16+
* Check if a number is even or not using & operator.
17+
*
18+
* @param number the number to be checked.
19+
* @return {@code true} if the given number is even, otherwise {@code false}.
20+
*/
21+
public static boolean isEvenFaster(int number) {
22+
return (number & 1) == 0;
23+
}
24+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.examplehub.maths;
2+
3+
import com.examplehub.utils.RandomUtils;
4+
import org.junit.jupiter.api.Test;
5+
6+
import static org.junit.jupiter.api.Assertions.*;
7+
8+
class EvenCheckTest {
9+
10+
@Test
11+
void isEven() {
12+
for (int i = -100; i <= 100; i += 2) {
13+
assertTrue(EvenCheck.isEven(i));
14+
}
15+
}
16+
17+
@Test
18+
void isEvenFaster() {
19+
for (int i = -100; i <= 100; i += 2) {
20+
assertTrue(EvenCheck.isEvenFaster(i));
21+
}
22+
}
23+
24+
@Test
25+
void testSpeed() {
26+
int[] ints = RandomUtils.randomInts(-1000, 1000, 1000);
27+
28+
long startTime = System.nanoTime();
29+
for (int j : ints) {
30+
boolean isEven = EvenCheck.isEven(j);
31+
}
32+
long slowTime = System.nanoTime() - startTime;
33+
34+
startTime = System.nanoTime();
35+
for (int anInt : ints) {
36+
boolean isEven = EvenCheck.isEven(anInt);
37+
}
38+
long fasterTime = System.nanoTime() - startTime;
39+
40+
assertTrue(fasterTime < slowTime);
41+
}
42+
}

0 commit comments

Comments
 (0)