In this HackerRank Print Prime Numbers problem solution 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
Problem solution MS SQL.
declare @result1 nvarchar(4000) = '2'
declare @n int = 1000
declare @i decimal(10,5) = 3
declare @boundary int
declare @isPrime int
declare @loop int
while @i < @n
begin
select @boundary = cast(Sqrt(@i) as int)
set @loop = 3
set @isprime = 1
if @i = 1 begin set @isprime = 0 end
if @i = 2 begin set @isprime = 1 end
if @i % 2 = 0 begin set @isprime = 0 end
while @loop <= @boundary and @isprime = 1
begin
if @i % @loop = 0 begin set @isprime = 0 end
set @loop = @loop + 2
end
if @isprime = 1
begin
set @result1 = @result1 + '&' + cast(cast(@i as int) as nvarchar(10))
end
set @i = @i + 1
end
select @result1
Problem solution in Oracle.
select listagg (l, '&')
WITHIN GROUP
(ORDER BY l) enames
from (
select 1 as x,l
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 l/m when trunc(l/m) then 'Y' end) = 2
order by l)
group by x;
Problem solution in DB2.
with dummy(id) as (
select 2 from SYSIBM.SYSDUMMY1
union all
select id + 1 from dummy where id < 1000
)
select '2&'||PN from (
select LISTAGG(PN,'&')PN from (
select PN from (select a.id PN, b.id FN, case when MOD(a.id, b.id) = 0 then 'N' else 'Y' end MS from dummy a inner join dummy b
on 1=1 and a.id > b.id
order by a.id, b.id)
group by PN
having LISTAGG(MS,'') not like '%N%'
)
)
;

0 Comments