Introduction
This problem is same as finding if a number is prime or not. But here we have to take a interval value and checks which numbers are prime between the interval using java methods and the interval value should be taken from the user.
Steps
- Take 2 inputs from the user
- Run a for loop from small small one to high one.
- Pass the loop value to isPrime() method.
- Print the value.
Java Code
package FunctionsOrMethods;
import java.util.Scanner;
public class PrimeBetweenInterval {
public static void main(String[] args) {
System.out.print("Please Enter the interval starting value of the interval: ");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
System.out.print("Now give the ending value of the interval: ");
int num2 = input.nextInt();
System.out.print("The prime numbers are: ");
// -----------------+++++++++ Prime Between Interval ++++++++++--------------
if ( num1 > num2){
int temp = num1;
num1 = num2;
num2 = temp;
}
for (int i = num1; i <= num2 ; i++) {
if (isPrime(i)){
System.out.print(" " + i);
}
}
}
private static boolean isPrime(int num) {
if(num <= 1){
return false;
}
double length = Math.sqrt(num);
for (int i = 2; i < length; i++) {
if (num % i == 0){
return false;
}
}
return true;
}
}
Top comments (0)