-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1260 from akshat-jjain/patch-1
Create Prime Checker.java
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import static java.lang.System.in; | ||
|
||
class Prime { | ||
void checkPrime(int... numbers) { | ||
for (int num : numbers) { | ||
if (isPrime(num)) { | ||
System.out.print(num + " "); | ||
} | ||
} | ||
System.out.println(); | ||
} | ||
|
||
boolean isPrime(int n) { | ||
if (n < 2) { | ||
return false; | ||
} else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below | ||
return true; | ||
} else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below | ||
return false; | ||
} | ||
int sqrt = (int) Math.sqrt(n); | ||
for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results | ||
if (n % i == 0) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
} |