본문 바로가기

코딩테스트/프로그래밍 기초 | 단순 반복문

[코드트리] 언제 끝날지 모르는 상황에서의 loop

3N + 1 수열

https://www.codetree.ai/trails/complete/curated-cards/intro-3n-plus-1-sequence/description

n = int(input())
cnt = 0
while True:
    if n == 1:
        break    
    if  n % 2 == 0:
        n = n // 2
        cnt += 1
    else:
        n = n * 3 + 1
        cnt += 1

print(cnt)

 

 

 

 

출력결과 3

https://www.codetree.ai/trails/complete/curated-cards/challenge-reading-k201521/description

1

 

 

 

출력결과 77

https://www.codetree.ai/trails/complete/curated-cards/challenge-reading-k201832/description

6

 

 

 

출력결과 78

https://www.codetree.ai/trails/complete/curated-cards/challenge-reading-k201833/description

4

 

 

 

출력결과 37

https://www.codetree.ai/trails/complete/curated-cards/challenge-reading-k201647/description

2

 

 

 

2의 거듭제곱수

https://www.codetree.ai/trails/complete/curated-cards/challenge-pow-of-2/description

N = int(input())
prod = 1
x = 0

while True:
    if N == prod:
        break
    prod *= 2
    x +=1
print(x)

 

 

 

 

조건에 따른 연산

https://www.codetree.ai/trails/complete/curated-cards/test-operatino-by-rule/description

n = int(input())
cnt = 0

while True:
    if n >= 1000:
        break
    if n % 2 == 0:
        n = n * 3 + 1
    else:
        n = n * 2 + 2
    cnt += 1
print(cnt)