We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
DECLARE
result VARCHAR2(32767) := '';
num INTEGER := 0;
-- Cursor to generate numbers from 1 to 1000
CURSOR c1 IS (SELECT LEVEL n FROM dual CONNECT BY LEVEL <= 1000);
-- Function to check if a number is prime
FUNCTION is_prime(n INTEGER) RETURN BOOLEAN IS
divisor INTEGER;
BEGIN
IF n < 2 THEN
RETURN FALSE;
ELSIF n IN (2, 3, 5) THEN
RETURN TRUE;
ELSIF MOD(n, 2) = 0 OR MOD(n, 3) = 0 OR MOD(n, 5) = 0 THEN
RETURN FALSE;
END IF;
divisor := 7;
WHILE divisor * divisor <= n LOOP
IF MOD(n, divisor) = 0 THEN
RETURN FALSE;
END IF;
divisor := divisor + 2; -- Skip even numbers
END LOOP;
RETURN TRUE;
END is_prime;
BEGIN
FOR c1_rec IN c1 LOOP
IF is_prime(c1_rec.n) THEN
result := result || c1_rec.n || '&';
END IF;
END LOOP;
-- Trim the last '&' and output result
dbms_output.PUT_LINE(TRIM(TRAILING '&' FROM result));
END;
/
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Print Prime Numbers
You are viewing a single comment's thread. Return to all comments →
In Oracle:
SET SERVEROUTPUT ON;
DECLARE result VARCHAR2(32767) := ''; num INTEGER := 0;
BEGIN FOR c1_rec IN c1 LOOP IF is_prime(c1_rec.n) THEN result := result || c1_rec.n || '&'; END IF; END LOOP;
END; /