Exercise:
Write a Java Program to create a function to display prime numbers between intervals.
Click Here to View the Solution!
public
class DisplayPrimeNumbers {
public static void main(String[] args) {
int low =
10, high =
1000;
while (low < high) {
if(checkPrimeNumber(low))
System.out.print(low +
" ");
++low;
}
}
// Function Definition
public static boolean checkPrimeNumber(int num) {
boolean flag =
true;
for(
int i =
2; i <= num/
2; ++i) {
if(num % i ==
0) {
flag =
false;
break;
}
}
return flag;
}
}
Click Here to View the Output!
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
Click Here to View the Explanation!
- This program is used to display the prime numbers between two intervals
low
andhigh
by using a function in Java. - The function used in the program “
checkPrimeNumber()
” is created within the program for finding the prime numbers. - The user-defined function “
checkPrimeNumber()
” takes the variablenum
as an argument and gives a Boolean value in return. - Initially, the
flag
for this method is set true, which means the number taken as a parameter is a prime number. Else, it is not. - After the while condition checks that the value of the interval low is smaller than the interval high, the
checkPrimeNumber
function applied on low, which will print the output within themain()
method according to the value returned by its defined function. - It is to be noted, the condition defined in the
checkPrimeNumber()
function iterates between 2 and num/2 . The reason being is that the greatest value divisible by a number is never greater than its half.