๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] N๊ฐœ์˜ ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ - Python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] N๊ฐœ์˜ ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ - Python

BAY 2023. 8. 13. 12:22
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/12953

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

์‚ฌ์ „ ์ง€์‹ 

python์—์„œ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜, ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ• 

- a,b์˜ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜ : math.gcd(a,b)

- a,b์˜ ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ : a*b/math.gcd(a,b)

 

์ฝ”๋“œ

๋‚ด ์ฝ”๋“œ(์ •๋‹ต)

from math import gcd

def solution(arr):
    stack = []
    for i in arr:
        if not stack:
            stack.append(i)
        else:
            a = stack.pop()
            stack.append(int(a*i/gcd(a, i)))
    return stack[0]

๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ฝ”๋“œ ๋ณด๋‹ˆ ๊ตณ์ด stack ์— ๋„ฃ์„ ํ•„์š”๊ฐ€ ์—†๊ธด ํ–ˆ๊ตฌ๋‚˜

 

๋‹ค๋ฅธ ์ฝ”๋“œ

from math import gcd

def solution(arr):      
    answer = arr[0]
    for n in arr:
        answer = n * answer / gcd(n, answer)

    return answer

 

๋น„๊ณ )

์ฒ˜์Œ ์ ‘๊ทผํ–ˆ๋˜ ๋ฐฉ๋ฒ•

๊ฐ ์š”์†Œ์˜ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜๋ฅผ ๋‹ค ๊ณฑํ•ด์„œ ์š”์†Œ๋“ค์˜ ๊ณฑ์—์„œ ๋‚˜๋ˆ ์ฃผ๋ฉด ๋˜์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•˜๊ธดํ–ˆ์Œ

from math import gcd
from functools import reduce

def solution(arr):
    answer = reduce(lambda x, y: x * y, arr)
    for i in range(len(arr)):
        for j in range(i+1, len(arr)):
            print(arr[i], arr[j], ": gcd = ", gcd(arr[i], arr[j]))
            answer /= gcd(arr[i], arr[j])
    return answer

# ์ด๋ ‡๊ฒŒ ํ•ด์ฃผ๊ณ  stack์— ์žˆ๋Š” ์š”์†Œ ์ค‘ ๋˜‘๊ฐ™๊ฑฐ๋‚˜, stack ์š”์†Œ์˜ ๊ณฑ์œผ๋กœ ํ•ด๋‹น ์ˆซ์ž๋ฅผ ๋งŒ๋“ค์–ด ๋‚ผ ์ˆ˜ ์žˆ์œผ๋ฉด appendํ•˜์ง€ ์•Š์œผ๋ฉด ๋  ๊ฑฐ ๊ฐ™์€๋ฐ ..

๊ทผ๋ฐ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜ ์ค‘์—์„œ ์ค‘๋ณต๋˜๋Š” ์š”์†Œ๋“ค์ด ์žˆ์œผ๋ฉด ๊ทธ๊ฑฐ ๋นผ๊ณ  ํ•ด์ค˜์•ผ ํ•˜๋Š”๊ฑธ ์•Œ์•˜์Œ

๋„ˆ๋ฌด ๋ณต์žกํ•ด์งˆ ๋ฟ๋”๋Ÿฌ ์‹œ๊ฐ„๋„ ์˜ค๋ž˜๊ฑธ๋ฆด ๊ฒƒ ๊ฐ™์•„์„œ(์‹œ๊ฐ„๋ณต์žก๋„) ๋‹ค๋ฅธ ์ ‘๊ทผ์„ ์‹œ๋„ํ•จ

๊ทธ๊ฒŒ ์œ„ ์ •๋‹ต ์ฝ”๋“œ

728x90