DEV Community

Cover image for Write a function that returns all prime numbers between two given numbers.
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on • Updated on

Write a function that returns all prime numbers between two given numbers.

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

  1. Take 2 inputs from the user
  2. Run a for loop from small small one to high one.
  3. Pass the loop value to isPrime() method.
  4. 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;
    }
}

Enter fullscreen mode Exit fullscreen mode

Output Image

Image description

Top comments (0)