-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRangeprime.java
More file actions
55 lines (41 loc) · 1.36 KB
/
Rangeprime.java
File metadata and controls
55 lines (41 loc) · 1.36 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
//wrong code
// import java.util.*;
// public class Rangeprime {
// public static void primesInRange(int n) {
// for(int i=2; i<=n; i++) {
// if(isPrime(i)) { //true
// System.out.print(i+" ");
// }
// }
// System.out.println();
// }
// public static void main(String args[]) {
// primesInRange(20);
// }
// }
//wirte method
import java.util.*;
public class Rangeprime {
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) return false; // 0 and 1 are not prime
for (int i = 2; i <= Math.sqrt(num); i++) { // Check up to the square root of num
if (num % i == 0) {
return false; // Found a divisor, not prime
}
}
return true; // No divisors found, it's prime
}
// Method to print all prime numbers in the range from 2 to n
public static void primesInRange(int n) {
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
public static void main(String args[]) {
primesInRange(50); // Change the number here to print primes in a different range
}
}