Repository navigation
Expand file tree
/
Copy pathPrimeFinder.java
More file actions
executable file
·84 lines (67 loc) · 2.16 KB
/
Copy pathPrimeFinder.java
File metadata and controls
executable file
·84 lines (67 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.Scanner;
public class PrimeFinder
{
/** Returns the number of prime numbers between lower and upper inclusive
* Precondition: 0 < lower <= upper
*/
public static int primesBetween(int lower, int upper)
{
/* to be implemented in part (a) */
int count = 0;
for (int i = lower; i <= upper; i++) {
if (isPrime(i))
count++;
}
return count;
}
/** Returns the difference between num and the closest prime number which
* is greater than or equal to num
* Precondition: num is positive
*/
public static int gapToNextPrime(int num)
{
int count = 0;
for (int i = num; !isPrime(i); i++) {
count++;
}
/* to be implemented in part (b) */
return count;
}
/** Returns true if the integer n is a prime number
* Precondition: n is positive
*/
// private static boolean isPrime(int n)
// {
// /* implementation not shown */
// if (n <= 1) {
// return false;
// }
// // if n % (n - 1) is equal to 0, n is not a prime number. if not, check whether n % (n - 2) is equal to 0. continue until n - (n - 1)
// for (int i = n - 1; i > 1; i--) {
// System.out.println("DEBUG: n = " + n + ", i = " + i + ", n % i = " + (n % i));
// if (n % i == 0) {
// return false;
// }
// }
// // if n is not divisible by a number that is between 2 to n - 1, n is a prime number
// return true;
// }
private static boolean isPrime(int n)
{
/* COMPLETE WORKING METHOD PROVIDED */
/* DO NOT MODIFY THE IMPLEMENTATION OF THIS METHOD*/
if(n <= 1) return false;
if(n==2) return true;
for(int i = 2; i < Math.sqrt(n)+1; i++) if(n%i == 0) return false;
return true;
}
public static void main(String[] args) {
int x = 47;
System.out.println("Is " + x + " a prime number? : " + isPrime(x));
int lower = 48;
int upper = 100;
System.out.println("Number of prime numbers between " + lower + " and " + upper + " inclusive: " + primesBetween(lower, upper));
int num = 90;
System.out.println("The difference between " + num + " and the closest prime number: " + gapToNextPrime(num));
}
}