SQL 기초 실무/SQL 알고리즘 문제

23.09.29. SQL Developer 알고리즘 문제 ⑪

잇꼬 2023. 10. 4. 11:04
728x90
반응형
SMALL

11. 최대 공약수

-- 예제121. 16과 24의 최대 공약수는?
select 16 as NUM1, 24 as NUM2
    from dual ;

-- 나눈 나머지 값
with num_d as ( select 16 as NUM1, 24 as NUM2
                            from dual )
select level, mod(NUM1, level), mod(NUM2, level) 
    from num_d
    connect by level <= NUM2 ;
    
-- 약수값 구하기
with num_d as ( select 16 as NUM1, 24 as NUM2
                            from dual )
select level, mod(NUM1, level), mod(NUM2, level) 
    from num_d
    where mod(NUM1, level) = 0 and mod(NUM2, level) = 0  
    connect by level <= NUM2 ; 

-- 최대값
with num_d as ( select 16 as NUM1, 24 as NUM2
                            from dual )
select max(level)
    from num_d
    where mod(NUM1, level) = 0 and mod(NUM2, level) = 0 
    connect by level <= NUM2 ;
    
accept p_n1 prompt ' 첫번째 숫자를 입력하세요.' ;
accept p_n2 prompt ' 두번째 숫자를 입력하세요.' ;

with num_d as ( select &p_n1 as NUM1, &p_n2 as NUM2 
                            from dual )
select max(level) as "최대 공약수" 
    from num_d
    where mod(NUM1, level) = 0 
    and mod(num2, level) = 0
    connect by level <= NUM2 ;

-- 문제1. 16과 24, 48 의 최대 공약수는? 
accept p_n1 prompt ' 첫번째 숫자를 입력하세요.' ;
accept p_n2 prompt ' 두번째 숫자를 입력하세요.' ;
accept p_n3 prompt ' 세번째 숫자를 입력하세요.' ;

with num_d as ( select &p_n1 as NUM1, &p_n2 as NUM2, &p_n3 NUM3 
                            from dual )
select max(level) as "최대 공약수" 
    from num_d
    where mod(NUM1, level) = 0 
    and mod(num2, level) = 0
    and mod(num3, level) = 0
    connect by level <= NUM3 ;

-- 문제2. 16과 24의 최소공배수는?
accept p_n1 prompt ' 첫번째 숫자를 입력하세요.' ;
accept p_n2 prompt ' 두번째 숫자를 입력하세요.' ;

with num_d as ( select &p_n1 as NUM1, &p_n2 as NUM2 
                            from dual )
select NUM1, NUM2, ( (NUM1/max(level)) * (NUM2/max(level))*max(level) ) as "최소 공배수"
    from num_d
    where mod(NUM1, level) = 0 and mod(NUM2, level) = 0
    connect by level <= NUM2 ;
728x90
반응형
LIST