Hacker Rank SQL

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.