# SQL | Looping exercise | Find first n primes using looping

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

You can learn how to do this exercise if you attend one of more of the courses listed below!

 Software ==> SQL  (198 exercises) Version ==> Any version of SQL Server Topic ==> Looping  (3 exercises) Level ==> Harder than average Classroom ==> Fast-track SQL  /  Advanced SQL Online ==> Fast-track SQL  /  Advanced SQL

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Your task is to write a query to show the first (say) 1000 primes.  Here's a suggested algorithm:

• Create an integer variable to hold the value whose primeness you're testing
• Use WHILE to loop until this integer is 1000, incrementing its value by 1 each time round the loop (let's call this number P)

Within this outer loop:

• Find out the square root of the number you're testing (use SQRT)
• Find out what the highest integer is just below this (use FLOOR) - let's call this X
• Try dividing each number from 1 up to and including X into P
• If we ever find a number such that P % X = 0 (ie that P leaves a remainder of 0 when divided by X) we have a non-prime, and we should flag this accordingly and break out of the loop The first few primes!

If you get this working, try incorporating a timestamp to see how long it took to run: The start of the time test - at the end, set @EndTime and use DateDiff(ms, @StartTime, @EndTime) to work out the difference in milliseconds

Save your hard work as Printing primes.sql, then close it down!

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
23 Apr 20 at 02:04

Holy ****!
That was awesome!

It took me waaaaay more time than I care to admit, but I got it.

I had to exclude 2 and 3 because of the use of FLOOR(SQRT(@P)) though.

There it is:

-------------------------------------------------
-- A little script to see how long it takes:
DECLARE @StartTime DATETIME
DECLARE @EndTime DATETIME
-- This is the start point. At the end we'll set the end point and calculate it
SET @StartTime = CURRENT_TIMESTAMP
-------------------------------------------------

/* Printing all prime numbers from 1 to 1,000 */

DECLARE @P INT                            --A variable to hold the number in check
DECLARE @counter INT                    -- A variable to hold the running numbers from 1 to @SQP
DECLARE @SQP INT                        -- the square root of @P (without the leftover)

SET @P = 1
SET @counter = 1

WHILE @P <= 1000                        --As long as @P <= 1000, do the following:
BEGIN
/* 1 */ SET @SQP = FLOOR(SQRT(@P))
/* 2 */ IF @P = 1
BEGIN
PRINT '1 is a special number. it''s neither Prime nor Composite Number'
END
/* 3 */ IF @P IN (2,3)
BEGIN
PRINT @P
END
ELSE           -- Now we're REALLY starting to check the number in @P
BEGIN
WHILE @counter <= @SQP
BEGIN
/* 1 */ IF @P % @counter = 0
BEGIN
/*    PRINT 'Not Prime' */
BREAK -- We can stop checking
END
ELSE
BEGIN
IF @counter = @SQP --That means it's a Prime
BEGIN
PRINT @P
BREAK -- We can stop checking
END
END
/* 2 */ IF @counter = @SQP
BEGIN
PRINT @P
BREAK -- We can stop checking
END
ELSE
BEGIN
SET @counter = @counter+1
END
END
END
/* 4 */BEGIN
SET @P = @P+1
SET @counter = 2
END
END
----------------------------------------
-- Calculating how long it took:
SET @EndTime = CURRENT_TIMESTAMP
PRINT ''
PRINT 'This process took '+ CAST(DateDiff(ms, @StartTime, @EndTime) AS VARCHAR) + ' milliseconds'
----------------------------------------