눈송이의 개발생활
[Programmers Lv.1]콜라츠 추측 & 최대공약수와 최소공배수 (Python) 본문
문제 - 콜라츠 추측
https://programmers.co.kr/learn/courses/30/lessons/12943
내 코드
def solution(num):
count = 0
while count <= 500:
if num == 1:
return count
if num % 2 == 0:
num /= 2
count += 1
else:
num = num * 3 + 1
count += 1
return -1
다른 사람 풀이
def solution(num):
for i in range(500):
if num == 1:
return i
num = num / 2 if num % 2 == 0 else num * 3 + 1
return -1
해결 방법
쉬운 문제여서 금방 풀 수 있었다!
✅ while말고 for문을 쓰는 방식도 익혀두자
✅ 한 줄로 쓸 수 있는 if문 익숙해지자
문제 - 최대공약수와 최소공배수
https://programmers.co.kr/learn/courses/30/lessons/12940
내 코드
from math import gcd
def lcm(x, y):
return x*y // gcd(x,y)
def solution(n, m):
answer = [gcd(n,m), lcm(n,m)]
return answer
다른 사람 풀이
def solution(a, b):
c, d = max(a, b), min(a, b)
t = 1
while t > 0:
t = c % d
c, d = d, t
answer = [c, int(a*b/c)]
return answer
해결 방법
나는 math 모듈에서 gcd()함수를 가져와서 사용했다.(최대공약수 찾아주는 함수)
lcm()은 gcd()만 사용하면 금방 만들 수 있어서 쉽게 최소공배수까지 찾을 수 있었다.
다른 사람의 풀이를 보니 유클리드 호제법을 사용해서 풀었다고 하길래 공부해보았다!
https://hihellosuah.tistory.com/74
'Algorithm > Programmers' 카테고리의 다른 글
[Programmers Lv.1]키패드 누르기 (Python) (0) | 2022.03.23 |
---|---|
[Programmers Lv.1]숫자 문자열과 영단어 (Python) (0) | 2022.03.23 |
[Programmers Lv.1]정수 제곱근 판별 & 정수 내림차순으로 배치하기 (Python) (0) | 2022.03.10 |
[Programmers Lv.1]짝수와 홀수 & 하샤드 수 (Python) (0) | 2022.03.07 |
[Programmers Lv.1]2016년 & 핸드폰 번호 가리기 (Python) (0) | 2022.03.05 |
Comments