• Home
  • About
    • JOOS photo

      JOOS

      Joos's blog

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

[백준] 2331번 : 반복수열 with python3

11 Nov 2018

Reading time ~1 minute

문제: https://www.acmicpc.net/problem/2331

solution 1

import sys
read = lambda : sys.stdin.readline().strip()

a, p = map(int, read().split())
d = []
while a not in d:
    d.append(a)
    a=sum([int(i)**p for i in str(a)])
print(d.index(a))

solution 2

  1. a의 각자리수에 p제곱을 set과 dict에 넣는다.
    • 여기에서 dict에서 key는 제곱값으로 설정하고 value에 그 제곱값이 나온 순서를 넣는다.
  2. while문을 통해 반복적으로 set과 dict에 넣는다
  3. 만약 set에 있는 것이 나오면 dict에 해당 숫자가 있는 index를 찾는다.
import sys

input = lambda : sys.stdin.readline().rstrip()
a, p = input().split()

check = set({a})
nums = {a:0}
idx = 0

while True:
    a=str(sum(int(c)**int(p)for c in a))
    if a in check:
        break

    check.add(a)
    idx +=1
    nums[a] = idx

print(nums[a])

solution 3

import sys
read = lambda : sys.stdin.readline().strip()

check = [0]* 146
def pow(x, p):
    ans = 1
    for i in range(p):
        ans *= x
    return ans

def next(a, p):
    ans = 0
    while a > 0:
        ans += pow(a%10, p)
        a //= 10
    return ans

def length(a, p, cnt):
    if check[a] != 0:
        return check[a] -1
        # 아닌 것의 전부터 시작하기 위해서 저것
    check[a] = cnt
    # 나온 숫자가 index고, 그 숫자가 나왔을 때의 index가 값이다.
    # 즉 check[a]-1이 값인 이유는 해당 숫자가 나왔을 때 전까지가 답이니까 이다.
    b = next(a, p)
    return length(b, p, cnt+1)
    # cnt늘린다.

a, p = map(int, read().split())
print(length(a, p, 1))



algorithm백준python Share Tweet +1