. A prime number is a number that is evenly divisible only by itself and 1. For example, the
number 5 is prime because it can be evenly divided only by 1 and 5. The number 6, however,
is not prime because it can be divided evenly by 1, 2, 4, and 6.
Write a method named as Prime, which takes an integer as an argument and returns true if the
argument is a prime number, or false otherwise. Also write main method that displays prime
numbers between 1 to 500
import java.util.*;
class App {
static boolean Prime(int number) {
int i;
if (number < 2) {
return false;
}
if (number == 2 || number == 3) {
return true;
}
for (i = 2; i <= Math.sqrt(number * 1.0); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Prime numbers between 1 to 500");
for (int i = 1; i <= 500; i++) {
if (Prime(i)) {
System.out.println(i);
}
}
keyboard.close();
}
}
Comments
Leave a comment