Skip to content

Commit 5e61a31

Browse files
committed
Prime Time
1 parent 818735d commit 5e61a31

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/medium/PrimeTime.java

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

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy