# Print Prime Numbers Solution

Hello Friends in this article i am gone to share Hacker Rank SQL Solutions with you | Print Prime Numbers Solution

Also Visit:  Draw The Triangle 2 Solution

#### Problem

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).

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

`2&3&5&7`

## Solution – Print Prime Numbers

##### MySQL Code
```DECLARE @Output AS VARCHAR(MAX) = '';
WITH digit(d)
AS
(
SELECT 0 AS d
UNION ALL
SELECT d+1 AS d FROM digit WHERE d < 9
)
SELECT
@Output += CAST(a.Number AS VARCHAR(3)) + '&'
FROM (
SELECT a.d * 100 + b.d*10 + c.d + 1 AS Number FROM digit a
CROSS JOIN digit b
CROSS JOIN digit c
) a
LEFT JOIN (
SELECT a.d * 100 + b.d*10 + c.d + 1 AS Number FROM digit a
CROSS JOIN digit b
CROSS JOIN digit c
) b ON SQRT(a.Number) >= b.Number AND b.Number > 1
WHERE  a.Number > 1
GROUP BY a.Number
HAVING ISNULL(SUM(CASE WHEN a.Number % b.Number = 0 THEN 1 ELSE 0 END),0) = 0
ORDER BY a.Number
PRINT SUBSTRING(@Output,1,LEN(@Output)-1)
;
```

### Prime numbers

Prime numbers are natural numbers that are divisible by only 1 and the number itself. In other words, prime numbers are positive integers greater than 1 with exactly two factors, 1 and the number itself. Some of the prime numbers include 2, 3, 5, 7, 11, 13, etc. Always remember that 1 is neither prime nor composite. Also, we can say that except for 1, the remaining numbers are classified as prime and composite numbers. All prime numbers are odd numbers except 2, 2 is the smallest prime number and is the only even prime number.

Prime numbers are the natural numbers greater than 1 with exactly two factors, i.e. 1 and the number itself.

Disclaimer: The above Problems are generated by Hacker Rank but the Solutions are Provided by NYANDER.COM. All Hacker Rank SQL Solutions Shared only for Educational and Learning Purpose.