Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
152 views

Java Program To Display Prime Numbers Between Intervals Using Function

This Java program prints all prime numbers between 20 and 50. It defines a checkPrimeNumber method that takes a number as a parameter and returns true if it is prime or false if it is not. In main, it loops from 20 to 50, checks each number with checkPrimeNumber, and prints any numbers that return true. The checkPrimeNumber method loops from 2 to half the number and returns false if any iteration fully divides the number without a remainder.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
152 views

Java Program To Display Prime Numbers Between Intervals Using Function

This Java program prints all prime numbers between 20 and 50. It defines a checkPrimeNumber method that takes a number as a parameter and returns true if it is prime or false if it is not. In main, it loops from 20 to 50, checks each number with checkPrimeNumber, and prints any numbers that return true. The checkPrimeNumber method loops from 2 to half the number and returns false if any iteration fully divides the number without a remainder.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Example: Prime Numbers Between Two Integers

public class Prime {

public static void main(String[] args) {

int low = 20, high = 50;

while (low < high) {


if(checkPrimeNumber(low))
System.out.print(low + " ");

++low;
}
}

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

Output

23 29 31 37 41 43 47

In the above program, we've created a function named checkPrimeNumber() which takes a
parameter num and returns a boolean value.

If the number is prime, it returns true . If not, it returns false .

Based on the return value, the number is printed on the screen inside the main() method.
Note that inside the checkPrimeNumber() method, we are looping from 2 to num/2. This is
because a number cannot be divided by more than it's half.

You might also like