Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit342d171

Browse files
committed
iluwatar#6: Is prime number check
1 parent6d538d4 commit342d171

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
importjava.util.List;
3636
importjava.util.zip.ZipEntry;
3737
importjava.util.zip.ZipOutputStream;
38-
38+
3939
/*
4040
* Java Snippets code
4141
*
@@ -312,4 +312,28 @@ public static int httpGet(URL address) throws IOException {
312312
HttpURLConnectioncon = (HttpURLConnection)address.openConnection();
313313
returncon.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+
publicstaticbooleanisPrime(intnumber) {
324+
if (number <3) {
325+
returntrue;
326+
}
327+
// check if n is a multiple of 2
328+
if (number %2 ==0) {
329+
returnfalse;
330+
}
331+
// if not, then just check the odds
332+
for (inti =3;i *i <=number;i +=2) {
333+
if (number %i ==0) {
334+
returnfalse;
335+
}
336+
}
337+
returntrue;
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
intresponseCode =Library.httpGet(newURL("http://www.google.com"));
279279
assertEquals(200,responseCode);
280280
}
281+
282+
/**
283+
* Tests for {@link Library#isPrime(int)}
284+
*/
285+
@Test
286+
publicvoidtestIsPrime() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp