Write a query to print all prime numbers less than or equal to 1000

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 \(\leq\) 10 would be:

2&3&5&7

 

———-SOLUTION———-

MYSQL

 

SELECT GROUP_CONCAT(NUMB SEPARATOR '&')
FROM (
    SELECT @num:=@num+1 as NUMB FROM
    information_schema.tables t1,
    information_schema.tables t2,
    (SELECT @num:=1) tmp
) tempNum
WHERE NUMB<=1000 AND NOT EXISTS(
        SELECT * FROM (
            SELECT @nu:=@nu+1 as NUMA FROM
                information_schema.tables t1,
                information_schema.tables t2,
                (SELECT @nu:=1) tmp1
                LIMIT 1000
            ) tatata
        WHERE FLOOR(NUMB/NUMA)=(NUMB/NUMA) AND NUMA<NUMB AND NUMA>1
    )

 

ORACLE

select listagg(Prime_Number,'&') within group(order by Prime_Number)
from (select L Prime_Number from
(select Level L 
from Dual
connect by Level <= 1000),
(select Level M
from Dual
connect by Level <= 1000)
where M <= L
group by L
having count(case when L/M = trunc(L/M) then 'Y' end) = 2
order by L);

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *