Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active May 10, 2024 14:41
Show Gist options
  • Save woodRock/b9259a1ae7a1b6b6ad09bd1afe1ca097 to your computer and use it in GitHub Desktop.
Save woodRock/b9259a1ae7a1b6b6ad09bd1afe1ca097 to your computer and use it in GitHub Desktop.
Write a query to print all prime numbers less than or equal to 1000. Print your result on a single line, and use the ampersand (&) character as your separator (instead of a space). Note: solved in SQL Sever MS.
DECLARE @I INT=2
DECLARE @PRIME INT=0
DECLARE @OUTPUT TABLE (NUM INT)
DECLARE @OUTPUT_STRING VARCHAR(MAX) = ''
WHILE @I<=1000
BEGIN
DECLARE @J INT = FLOOR(SQRT(@I))
SET @PRIME=1
WHILE @J>1
BEGIN
IF @I % @J=0
BEGIN
SET @PRIME=0
END
SET @J=@J-1
END
IF @PRIME =1
BEGIN
INSERT @OUTPUT VALUES (@I)
END
SET @I=@I+1
END
SELECT STRING_AGG(NUM,'&') FROM @OUTPUT;
@shreyaarajan
Copy link

Can you give an explanation on how you have formed the code? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment