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

Commit 818735d

Browse files
committed
Primes
1 parent c50806a commit 818735d

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎src/medium/Primes.java‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package medium;
2+
3+
/**
4+
* Have the function Primes(num) take the num parameter being passed
5+
* and return the string true if the parameter is a prime number,
6+
* otherwise return the string false. The range will be between 1 and 2^16.
7+
*/
8+
public class Primes {
9+
10+
private static boolean isPrime(int num) {
11+
// prime numbers are greater than 1
12+
if (num <= 1) {
13+
return false;
14+
}
15+
// 2 is an only even prime number
16+
// http://mathworld.wolfram.com/EvenPrime.html
17+
if (num == 2) {
18+
return true;
19+
}
20+
// eliminate all even numbers to reduce time complexity
21+
// (cannot be a prime number if is divisible by 2)
22+
if (num % 2 == 0) {
23+
return false;
24+
}
25+
// no need to check the entire range from 0 to num
26+
// (square root of num) + 1 is the sufficient upper limit
27+
// which greatly reduces time complexity
28+
double upper = Math.sqrt(num) + 1;
29+
// since the even numbers are eliminated, we can check the odd numbers only
30+
for (int i = 3; i < upper; i += 2) {
31+
if (num % i == 0) {
32+
// not a prime number
33+
return false;
34+
}
35+
}
36+
// must be a prime number!
37+
return true;
38+
}
39+
40+
/**
41+
* Primes function.
42+
*
43+
* @param num input number
44+
* @return "true" if is a prime number
45+
*/
46+
private static String primes(int num) {
47+
return isPrime(num) ? "true" : "false";
48+
}
49+
50+
/**
51+
* Entry point.
52+
*
53+
* @param args command line arguments
54+
*/
55+
public static void main(String[] args) {
56+
String result1 = primes(195);
57+
System.out.println(result1);
58+
String result2 = primes(197);
59+
System.out.println(result2);
60+
}
61+
62+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /