File tree Expand file tree Collapse file tree
main/java/com/examplehub/maths
test/java/com/examplehub/maths Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments