Question

Print prime number in given range using recursion

				
					ENTER LOWER RANGE:1
ENTER UPPER RANGE:50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class primeNumber
{
    public static boolean checkPrime(long n,long i)
    {
        if(n<2)
        {
            return false;   
        }
        /*Check if i is greater than n/2 because if any number is divisible by another number till another number is less than or equal to num/2*/
        else if(i>(n/2)) 
        {
            return true;
        }

        else if(n%i==0)
        {
            return false;  
        }
        else
        {
            return  checkPrime(n,(i+1));
        }
    }

    public static void main()
    {
        long lowerRange=0,upperRange=0,i=0;

        Scanner sc=new Scanner(System.in);
        System.out.print("ENTER LOWER RANGE:");
        lowerRange=sc.nextLong();
        System.out.print("ENTER UPPER RANGE:");
        upperRange=sc.nextLong();
        System.out.println("PRIME NUMBERS BETWEEN "+lowerRange+" AND "+upperRange+":");
        for(i=lowerRange;i<=upperRange;i++)
        {

            if(checkPrime(i,2)==true)
            {
                System.out.print(i+" ");
            }

        }

    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *