Compute Prime Numbers (in a range)
-- PL/SQL code to compute prime number in a
-- range of numbers between 1 and 25 
-- (upper limit -> any random value)
DECLARE
  v_idx  PLS_INTEGER := DBMS_RANDOM.value(1,25);
  v_val  PLS_INTEGER := 0;

FUNCTION is_prime(i_num IN PLS_INTEGER)
RETURN PLS_INTEGER AS
   v_div    PLS_INTEGER := 1;
   o_int    PLS_INTEGER;
BEGIN  
  WHILE v_div < i_num LOOP
   v_div := v_div+1;
   IF MOD(i_num,v_div) = 0 AND v_div < i_num THEN 
      EXIT;
   END IF;
  END LOOP;
  IF v_div = i_num THEN
     o_int := i_num;
  END IF;
  RETURN o_int;
END is_prime;

BEGIN
 DBMS_OUTPUT.PUT_LINE('Prime Number '||
   'Between 1 to '||v_idx);

 WHILE v_val < v_idx LOOP
  v_val := v_val+1;

  IF is_prime(v_val) IS NOT NULL THEN
   IF v_val = 1 THEN
    DBMS_OUTPUT.PUT(is_prime(v_val));
   ELSE
    DBMS_OUTPUT.PUT(', '||is_prime(v_val));
   END IF;
  END IF;

 END LOOP;
 DBMS_OUTPUT.PUT_LINE(' ');
EXCEPTION
 WHEN OTHERS THEN   RAISE;
END;
/
  Compute Prime Numbers Output


Oracle registered trademark of Oracle Corporation.

Last Revised On: July 5, 2013

  373