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.
Print Prime Numbers
Print Prime Numbers
Sort by
recency
|
1285 Discussions
|
Please Login in order to post a comment
SET SERVEROUTPUT ON; DECLARE prime_ls SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST(); is_prime BOOLEAN; rst_str VARCHAR2(4000) := ''; BEGIN FOR i IN 2..1000 LOOP is_prime := TRUE; FOR J IN 2..FLOOR(SQRT(i)) LOOP IF MOD(i, j) = 0 THEN is_prime := false; exit; END IF; END LOOP; IF is_prime THEN prime_ls.EXTEND; prime_ls(prime_ls.LAST) := TO_CHAR(i); END IF; END LOOP; FOR idx in 1..prime_ls.COUNT LOOP IF idx > 1 THEN rst_str := rst_str || '&'; END IF; rst_str := rst_str || prime_ls(idx); END LOOP; DBMS_OUTPUT.PUT_LINE(rst_str); END; /
WITH A AS ( SELECT LEVEL AS L FROM DUAL CONNECT BY LEVEL <= 1000 ) SELECT LISTAGG(L,'&') WITHIN GROUP (ORDER BY L) FROM ( SELECT L FROM A MAIN WHERE NOT EXISTS ( SELECT 1 FROM A SUB WHERE MAIN.L>SUB.L AND MOD(MAIN.L,L)=0 AND SUB.L>1 ) AND L<>1 );
WITH RECURSIVE Numbers AS ( SELECT 2 AS num UNION ALL SELECT num + 1 FROM Numbers WHERE num < 1000 ), nonprime AS ( SELECT N1.num FROM Numbers N1 JOIN Numbers N2 ON N2.num < N1.num AND N1.num % N2.num = 0 ) SELECT GROUP_CONCAT(num SEPARATOR '&') AS concatenated_value FROM Numbers WHERE num NOT IN (SELECT num FROM nonprime)
I’m encountering an issue while running my query on HackerRank. The same query works perfectly in Oracle SQL Developer, but when I try to run it on HackerRank, I get an error. The query is designed to find prime numbers up to 1000 and list them separated by &.
Here is my query:
WITH numbers AS ( SELECT LEVEL AS num FROM dual CONNECT BY LEVEL <= 1000 ),
prime_candidates AS ( SELECT num FROM numbers WHERE num > 1 ),
primes AS ( SELECT num FROM prime_candidates np
WHERE NOT EXISTS ( SELECT 1 FROM prime_candidates pc WHERE pc.num < np.num AND MOD(np.num, pc.num) = 0 ) )
SELECT LISTAGG(num, '&') WITHIN GROUP (ORDER BY num) AS prime_numbers FROM primes; It works fine in Oracle SQL Developer, but on HackerRank, I get the error:
output:-
SP2-0734: unknown command beginning "prime_cand..." - rest of line ignored. SP2-0734: unknown command beginning "primes AS ..." - rest of line ignored. ORA-00942: table or view does not exist
Could anyone explain why I get this error on HackerRank and if there’s something wrong with my query? I am using Oracle SQL for this query.