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.
CTE numbers: Generates numbers from 2 to 1000.
CTE primes: Filters only prime numbers by checking divisibility — if no number less than n divides n, it’s prime.
GROUP_CONCAT(... SEPARATOR '&'): Joins all primes in one line using &.
WITH RECURSIVE numbers AS (
SELECT 2 AS n
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 1000
),
primes AS (
SELECT n FROM numbers AS a
WHERE NOT EXISTS (
SELECT 1 FROM numbers AS b
WHERE b.n < a.n AND b.n > 1 AND MOD(a.n, b.n) = 0
)
)
SELECT GROUP_CONCAT(n SEPARATOR '&') AS prime_numbers
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 →
CTE numbers: Generates numbers from 2 to 1000. CTE primes: Filters only prime numbers by checking divisibility — if no number less than n divides n, it’s prime. GROUP_CONCAT(... SEPARATOR '&'): Joins all primes in one line using &.
WITH RECURSIVE numbers AS ( SELECT 2 AS n UNION ALL SELECT n + 1 FROM numbers WHERE n < 1000 ), primes AS ( SELECT n FROM numbers AS a WHERE NOT EXISTS ( SELECT 1 FROM numbers AS b WHERE b.n < a.n AND b.n > 1 AND MOD(a.n, b.n) = 0 ) ) SELECT GROUP_CONCAT(n SEPARATOR '&') AS prime_numbers FROM primes;