Member-only story
Print Prime Numbers — HackerRank Advanced SQL
Oct 21, 2020
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 = 2WHILE @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))