File tree Expand file tree Collapse file tree 2 files changed +38
-1
lines changed
Expand file tree Collapse file tree 2 files changed +38
-1
lines changed Original file line number Diff line number Diff line change 3535import java .util .List ;
3636import java .util .zip .ZipEntry ;
3737import java .util .zip .ZipOutputStream ;
38-
38+
3939/*
4040 * Java Snippets code
4141 *
@@ -312,4 +312,28 @@ public static int httpGet(URL address) throws IOException {
312312 HttpURLConnection con = (HttpURLConnection ) address .openConnection ();
313313 return con .getResponseCode ();
314314 }
315+
316+ /**
317+ * Checks if given number is a prime number
318+ * Prime number is a number that is greater than 1 and divided by 1 or itself only
319+ * Credits: https://en.wikipedia.org/wiki/Prime_number
320+ * @param number number to check prime
321+ * @return true if prime
322+ */
323+ public static boolean isPrime (int number ) {
324+ if (number < 3 ) {
325+ return true ;
326+ }
327+ // check if n is a multiple of 2
328+ if (number % 2 == 0 ) {
329+ return false ;
330+ }
331+ // if not, then just check the odds
332+ for (int i = 3 ; i * i <= number ; i += 2 ) {
333+ if (number % i == 0 ) {
334+ return false ;
335+ }
336+ }
337+ return true ;
338+ }
315339}
Original file line number Diff line number Diff line change @@ -278,4 +278,17 @@ public void testHttpGet() throws IOException {
278278 int responseCode = Library .httpGet (new URL ("http://www.google.com" ));
279279 assertEquals (200 , responseCode );
280280 }
281+
282+ /**
283+ * Tests for {@link Library#isPrime(int)}
284+ */
285+ @ Test
286+ public void testIsPrime () {
287+ assertTrue (Library .isPrime (2 ));
288+ assertTrue (Library .isPrime (3 ));
289+ assertTrue (Library .isPrime (17 ));
290+ assertTrue (Library .isPrime (97 ));
291+ assertFalse (Library .isPrime (4 ));
292+ assertFalse (Library .isPrime (100 ));
293+ }
281294}
You can’t perform that action at this time.
0 commit comments