SQL/HackerRank

Draw The Triangle 1,Draw The Triangle 2,Print Prime Numbers

쿄코코 2022. 12. 20. 19:24
반응형

 

Draw The Triangle 1 📝 

https://www.hackerrank.com/challenges/draw-the-triangle-1/problem?isFullScreen=true 

  • information.table : 데이터베이스에 존재하는 테이블에 대한 정보 제공.

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

* * * * * 
* * * * 
* * * 
* * 
*

Write a query to print the pattern P(20).

 

set @number = 21; -- number 21로 지정
select repeat('* ', @number := @number - 1) 
from information_schema.tables;

 


 

Draw The Triangle 2 📝 

https://www.hackerrank.com/challenges/draw-the-triangle-2/problem?isFullScreen=true 

  • information.table : 데이터베이스에 존재하는 테이블에 대한 정보 제공.
  • 어....초면인 설명인데 할말이 없는 설명이다...⭐️

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

* 
* * 
* * * 
* * * * 
* * * * *

Write a query to print the pattern P(20).

 

 

set @number = 0;
select repeat('* ', @number := @number + 1) 
from information_schema.tables
LIMIT 20;

 


 

Print Prime Numbers 📝 

https://www.hackerrank.com/challenges/print-prime-numbers/problem?isFullScreen=true 

  • 1 . 2부터 1000까지 채우기(1은 어차피 소수가 아니므로 제외)
  • 2부터 차례대로 나누었을 때 나누어지는 값 제외시키기( 본인 값은 제외 num != k )
  • 출력 시 &로 이어서 붙이기

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  would be:

2&3&5&7

 

CREATE TABLE nonprimenumber(num INT PRIMARY KEY); --빈테이블 만들기

-- 2부터 1000까지 채우기
DELIMITER $$ 
CREATE PROCEDURE fill1000()
BEGIN
    DECLARE i INT DEFAULT 2; 
    WHILE (i <= 1000) DO
        INSERT INTO nonprimenumber VALUE (i); 
        SET i = i + 1; 
    END WHILE;
END$$
DELIMITER ;


DELIMITER $$
CREATE PROCEDURE loop_test()
BEGIN 
    DECLARE k INT DEFAULT 2;
    WHILE(k <= 1000) DO  
        DELETE FROM nonprimenumber WHERE num%k = 0 AND num!=k ;
        SET k = k+1 ;
    END WHILE;
END$$
DELIMITER ;

CALL fill1000();
CALL loop_test();
SELECT GROUP_CONCAT(num separator '&') FROM nonprimenumber;
반응형