Java method that lists all primes between 2 and 100
- 2020-04-01 03:59:23
- OfStack
This article illustrates a Java method for listing all primes between 2 and 100. Share with you for your reference. The specific implementation method is as follows:
//TestPrime.java :
public class TestPrime {
public static boolean isPrime(int num) {
for(int i = 2; i <= Math.sqrt(num); i++) {
//Program default 2 is prime, when j=2, the loop does not execute
if(num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
for(int j = 2; j <= 100; j++) {
if(TestPrime.isPrime(j)) {
System.out.println(j + " is a prime");
}
}
}
}
I hope this article has been helpful to your Java programming.