백준 9417 최대 GCD

김민영·2023년 1월 5일
0

알고리즘

목록 보기
30/125

계획

  • 브루트포스. 모든 경우를 비교할 것.
  • 최대공약수 구하는 함수 만들기.
import sys
input = sys.stdin.readline
N = int(input())

def gcd(x, y):
    r = x % y
    while r != 0:
        x = y
        y = r
        r = x % y
    return y

for _ in range(N):
    max = 1
    lst = list(map(int, input().split()))
    length = len(lst)
    for i in range(length):
        for j in range(i+1, length):
            if i != j:
                g = gcd(lst[i], lst[j])
                if max < g:
                    max = g
    print(max)
  • 모든 경우를 비교해야 하기에 조합의 가짓수를 계산해야할지 고민했다.
  • 최대공약수 구하는 데에는 두 수의 조합만이 필요하므로 이중 반복문으로 해결 가능하다.
  • 간단하게 생각하는 연습이 필요할 것 같다.
profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글