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.
SET @N = 1000;
WITH RECURSIVE numbers AS (
SELECT 2 AS num
UNION ALL
SELECT num + 1
FROM numbers
WHERE num + 1 <= @N
),
primes AS (
SELECT num
FROM numbers n1
WHERE NOT EXISTS (
SELECT 1
FROM numbers n2
WHERE n2.num < n1.num AND n1.num % n2.num = 0 AND n2.num > 1
)
)
SELECT GROUP_CONCAT(num SEPARATOR '&') AS primes
FROM primes;
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 →
MySQL:-
SET @N = 1000; WITH RECURSIVE numbers AS ( SELECT 2 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num + 1 <= @N ), primes AS ( SELECT num FROM numbers n1 WHERE NOT EXISTS ( SELECT 1 FROM numbers n2 WHERE n2.num < n1.num AND n1.num % n2.num = 0 AND n2.num > 1 ) ) SELECT GROUP_CONCAT(num SEPARATOR '&') AS primes FROM primes;