Codewars: Achieve mastery through coding challenge
Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!
www.codewars.com
문제
Write a SELECT query which will return all prime numbers smaller than 100 in ascending order.
Your query should return one column named prime.
코드
CREATE OR REPLACE FUNCTION pri(n INTEGER)
RETURNS INTEGER AS $$
DECLARE
i INTEGER := 1;
cnt INTEGER := 0;
BEGIN
FOR i IN 1..100
LOOP
i := i+1;
if n % i = 0 and n != i THEN
BEGIN
cnt := cnt + 1;
EXIT;
END;
END IF;
END LOOP;
RETURN cnt;
END;
$$ LANGUAGE plpgsql;
CREATE TABLE my_table(
list INTEGER PRIMARY KEY
);
INSERT INTO my_table SELECT j FROM generate_series(2,100) j;
SELECT list as prime FROM my_table WHERE pri(list) = 0;
함수를 만들어서 풀었는데…
함수로 풀지 말라며 문구가 떴다.
SELECT i as prime
FROM
generate_series(2, 100) as i
WHERE
i IN (2,3,5,7) OR
i % 2 != 0 and
i % 3 != 0 and
i % 5 != 0 and
i % 7 != 0
설명
좀 원시적인 풀이지만, 100까지의 자연수에서 소수를 찾기만 하면 되는 것이므로, 2, 3, 5, 7로 나누어 떨어지지 않는 수를 골라냈다.
'컴퓨터과학 > Algorithm' 카테고리의 다른 글
[Python] [백준] 2490번 윷놀이 (0) | 2021.12.01 |
---|---|
[SQL] [Codewars] 7Kyu - SQL: Regex Replace (0) | 2021.11.04 |
[SQL] [Codewars] 7kyu - Simple Fun #74: Growing Plant (0) | 2021.11.04 |