Java program to display prime numbers between two intervals
Here's a Java program that displays prime numbers between two intervals:
import java.util.Scanner; public class PrimeNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); System.out.println("Prime numbers between " + num1 + " and " + num2 + " are: "); for (int i = num1; i <= num2; i++) { if (isPrime(i)) { System.out.print(i + " "); } } } public static boolean isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } }Source:www.theitroad.com
Explanation:
The program prompts the user to enter two numbers using the Scanner
class. The numbers are stored in the num1
and num2
variables, respectively.
The program then prints the message "Prime numbers between num1
and num2
are: " to the console.
The program then uses a for
loop to iterate over all integers between num1
and num2
. For each integer i
, the isPrime
function is called to check if i
is a prime number. If it is, the value of i
is printed to the console.
The isPrime
function takes an integer n
as its argument and returns a boolean value indicating whether n
is a prime number or not. The function first checks if n
is less than or equal to 1, in which case it returns false
. If n
is greater than 1, the function uses a for
loop to check if n
is divisible by any integer between 2 and the square root of n
. If n
is divisible by any of these integers, the function returns false
. Otherwise, the function returns true
.