Practice Question 4

Home / Java Practice Question / Practice Question 4

Practice Question 4


Question 4. Write a Program to generate all primes between M and N including M and N where M and N are two integers.

Program


class Solution {

    ArrayList<Integer> primeRange(int M, int N) {

        ArrayList<Integer>al=new ArrayList<>();

        for(int i=M;i<=N;i++)

        {

            if(isPrime(i)==true)

              al.add(i);

        }

        return al;

    }

    public static boolean isPrime(int n)

    {

        if(n<=1) return false;

        

        if(n==2 || n==3) return true;

        

        if(n%2==0 || n%3==0) return false;

        

        for(int i=5;i<=Math.sqrt(n);i=i+6)

        {

            if(n%i==0 || n%(i+2)==0) 

                return false;

        }

        return true;

    }

}