Write a Java Program to Display Prime Numbers Between Intervals Using Function

As a Java programmer, you may be required to display prime numbers between intervals using functions.

In this tutorial, we will discuss how to write a Java program to display prime numbers between intervals using a function.


What are Prime Numbers?

Prime numbers are natural numbers greater than 1 that are only divisible by 1 and themselves.

For example, 2, 3, 5, 7, 11, 13, 17, 19, and 23 are prime numbers.

Writing a Java Program to Display Prime Numbers Between Intervals Using Function

To write a Java program to display prime numbers between intervals using a function, you can follow these steps:

Step 1: Create a function to check whether a number is prime or not

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; }

This function takes a number as an argument and checks whether it is prime or not.

It returns true if the number is prime and false otherwise.

Create a function to display prime numbers between intervals

public static void displayPrimeNumbers(int start, int end) { for (int i = start; i &lt;= end; i++) { if (isPrime(i)) { System.out.print(i + " "); } } }

This function takes two arguments, start and end, and displays all the prime numbers between these intervals.

It calls the isPrime() function to check whether a number is prime or not.

Call the displayPrimeNumbers() function

Now that you have created the displayPrimeNumbers() function, you can call it from the main() function as follows:

public static void main(String[] args) { int start = 10; int end = 50; System.out.printf("Prime numbers between %%d and %%d are: ", start, end); displayPrimeNumbers(start, end); }

In this example, we have set the values of start and end as 10 and 50, respectively. The program will display all the prime numbers between these intervals.


Conclusion

In conclusion, displaying prime numbers between intervals using functions is a simple task in Java.

By following the steps outlined in this tutorial, you can easily write a Java program to display prime numbers between intervals using functions.

Remember to always test your code before running it in a production environment.