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.

The answer to the exercise will be included and explained 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
Courses ==> 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

If it helps, here's what you should see to start with:

SQL exercise - Looping (image 1)

The first few primes!

If you get this working, try incorporating a timestamp to see how long it took to run:

SQL exercise - Looping (image 2)

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!

This page has 0 threads Add post