Member-only story

Print Prime Numbers — HackerRank Advanced SQL

--

Write a query to print all prime numbers less than or equal to . Print your result on a single line, and use the ampersand () character as your separator (instead of a space).

For example, the output for all prime numbers would be:

2&3&5&7

Solution

Mysql Server

DECLARE @table TABLE (PrimeNumber INT)DECLARE @final AS VARCHAR(1500)
SET @final = ''
DECLARE @counter INT
SET @counter = 2
WHILE @counter <= 1000
BEGIN
IF NOT EXISTS (
SELECT PrimeNumber
FROM @table
WHERE @counter % PrimeNumber = 0)
BEGIN
INSERT INTO @table SELECT @counter
SET @final = @final + CAST(@counter AS VARCHAR(20))+'&'
END
SET @counter = @counter + 1
END
/* remove last & */
SELECT SUBSTRING(@final,0,LEN(@final))

--

--

Amber Ivanna Trujillo
Amber Ivanna Trujillo

Written by Amber Ivanna Trujillo

I am Executive Data Science Manager. Interested in Deep Learning, LLM, Startup, AI-Influencer, Technical stuff, Interviews and much more!!!

No responses yet