Skip to content

Commit 342d171

Browse files
committed
iluwatar#6: Is prime number check
1 parent 6d538d4 commit 342d171

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/main/java/Library.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import java.util.List;
3636
import java.util.zip.ZipEntry;
3737
import 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
}

src/test/java/LibraryTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)