Prime numbers, those greater than 1 with no divisors other than 1 and themselves, are a fundamental concept in mathematics and computer science. Identifying prime numbers within a specific range involves checking if numbers within that range have any divisors other than 1 and themselves. This task can provide a practical grasp of loops and conditionals in programming.
In this article, you will learn how to create a Java program to display prime numbers between two given intervals using functions. The examples will demonstrate how to define a function for checking primality and utilize this function to filter and print prime numbers within a specified range.
Start by defining a function named isPrime
that takes an integer number
as its parameter. This function will return true
if the number is a prime and false
otherwise.
Ensure the function handles edge cases, such as numbers less than 2, which are not prime by definition.
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
This function starts by discarding any number less than or equal to 1. It then checks every number up to the square root of number
for divisibility. If any divisor is found, it returns false
; otherwise, it returns true
.
Define the main
method where you prompt the user to enter the interval limits - start
and end
.
Loop through the range from start
to end
, and use the isPrime
function to check each number. If it is prime, print the number.
import java.util.Scanner;
public class PrimeNumbersBetweenIntervals {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the start of the interval: ");
int start = scanner.nextInt();
System.out.print("Enter the end of the interval: ");
int end = scanner.nextInt();
System.out.printf("Prime numbers between %d and %d are:%n", start, end);
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
scanner.close();
}
}
In this code, Scanner
is used to collect integer inputs for start
and end
. The program then iterates from start
to end
, printing each number that isPrime
identifies as a prime.
The program you've just explored effectively displays prime numbers between user-defined intervals using a dedicated function to determine primality. Through this exercise, you enhance your understanding of functions, loops, and conditionals in Java. Incorporate this logic into broader applications where understanding and manipulating prime numbers are crucial. By following the outlined steps and explanations, you ensure your Java programming skills remain sharp and efficient in tackling various algorithmic challenges.