Ronnie72428

Prime Number (Recursion)

Nov 30th, 2021
656
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.*;
  2.  
  3. class PrimeRecursion{
  4.     public static void main(){
  5.         Scanner sc = new Scanner(System.in);
  6.        
  7.         System.out.print("Enter the lower limit: ");
  8.         int range_low = sc.nextInt();
  9.        
  10.         System.out.print("Enter the upper limit: ");
  11.         int range_high = sc.nextInt();
  12.        
  13.         for(int i = range_low; i <= range_high; i++){
  14.             if(IsPrime(i, 2))
  15.                 System.out.println(i);
  16.         }
  17.        
  18.     }
  19.    
  20.     public static boolean IsPrime(int n, int i){
  21.        
  22.         //  1 & 2 are prime numbers so direct return of boolean datatype //
  23.         if (n <= 2)
  24.             return (n == 2 || n == 1) ? true : false;
  25.            
  26.         //  Recursion checking of number by i getting incremented in every recursion //
  27.         if (n % i == 0)
  28.             return false;
  29.            
  30.         /*  If the divisor gets greater than the number itself without triggering a return boolean, then it is a prime number
  31.             and will return true. */
  32.         if (i * i > n)
  33.             return true;
  34.        
  35.         // Calling the same function but with the divisor incremented by 1. //
  36.         return IsPrime(n, i + 1);
  37.     }
  38. }
RAW Paste Data