본문 바로가기

Algorithm

[그래프] boj 2331 - 반복수열

백준 2331은 DFS로 풀었다. 연산 방식에 변화가 없기 때문에 수열에 이미 존재하는 수가 다시 등장한다면 반복이 확실하다. 이 생각을 가져야 풀 수 있는 문제 같다. 

 

스터디 이후 생각: str으로 변환해서 새 변수에 넣고, 그 변수 째로 for문을 돌았다면 코드 가독성을 높일 수 있었다.

[i : i+1] 대신 for x in string의 x

 

import sys


def calcNew(n):
    temp = 0
    for i in range(len(str(numbers[n-1]))):
        temp += int(str(numbers[n - 1])[i:i + 1]) ** p
    return temp


a, p = map(int, sys.stdin.readline().split(' '))
n = 0
numbers = []
numbers.append( a)
loopStartsAt = 0

while True:
    n += 1
    tempNum = calcNew(n)
    if tempNum in numbers:
        loopStartsAt = numbers.index(tempNum)
        break
    else:
        numbers.append(tempNum)

print(loopStartsAt)