
Introduction
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.
Displaying Prime Numbers Between Intervals
Defining the Prime-checking Function
- Start by defining a function named - isPrimethat takes an integer- numberas its parameter. This function will return- trueif the number is a prime and- falseotherwise.
- Ensure the function handles edge cases, such as numbers less than 2, which are not prime by definition. java- 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 - numberfor divisibility. If any divisor is found, it returns- false; otherwise, it returns- true.
Creating the Main Function to Display Primes
- Define the - mainmethod where you prompt the user to enter the interval limits -- startand- end.
- Loop through the range from - startto- end, and use the- isPrimefunction to check each number. If it is prime, print the number.java- 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, - Scanneris used to collect integer inputs for- startand- end. The program then iterates from- startto- end, printing each number that- isPrimeidentifies as a prime.
Conclusion
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.