ChocolatesByNumbers

HeeSeong·2021년 6월 17일
0

Codility

목록 보기
30/34
post-thumbnail

🔗 문제 링크

https://app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/start/


❔ 문제 설명


Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N − 1.

You start to eat the chocolates. After eating a chocolate you leave only a wrapper.

You begin with eating chocolate number 0. Then you omit the next M − 1 chocolates or wrappers on the circle, and eat the following one.

More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).

You stop eating when you encounter an empty wrapper.

For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.

The goal is to count the number of chocolates that you will eat, following the above rules.

Write a function:

def solution(N, M)

that, given two positive integers N and M, returns the number of chocolates that you will eat.

For example, given integers N = 10 and M = 4. the function should return 5, as explained above.


⚠️ 제한사항


  • N and M are integers within the range [1..1,000,000,000].



💡 풀이 (언어 : Python)


정답률은 통과했지만 시간복잡도에서 통과를 실패했다. 시간을 줄여보기 위해 원래 empty 리스트에 있는지 조회하는 부분을 딕셔너리도 사용해보고 했지만 역부족이었다. 타인의 풀이를 공부했다. 이 문제는 단순히 N까지의 최대 공약수를 구하고 N을 최대 공약수로 나누어 개수를 구하는 문제이다. (N * M) / 최대공약수 가 최소공배수 공식인데, 최소 공배수를 M으로 나누어 몇번 턴에 최소공배수 도달하는지가 답이다. 정답은 이 공식을 정리하면 (N / 최대 공약수) 으로 구한 같은 답이다.

내 풀이

def solution(N, M):
    dic = dict()
    dic[0] = 1
    empty = [0]
    nextM = M
    while True:
        if nextM // N != 0:
            nextM = nextM % N
        
        if dic.get(nextM) != None:
            break
        else:
            dic[nextM] = 1
            empty.append(nextM)
            nextM += M

    return len(empty)

배울만한 풀이

def solution(N, M):
    # 최대 공약수 구하기
    a, b = N, M
    while b > 0:
        a, b = b, a % b
	# a는 최대 공약수
    return N // a
profile
끊임없이 성장하고 싶은 개발자

2개의 댓글

comment-user-thumbnail
2021년 8월 29일

I don't really like sweets.

답글 달기
comment-user-thumbnail
2021년 8월 29일

I love sweets, but also not everything, because I have been eating sweets for as long as I can remember, and therefore I have already tried almost everything. I wanted to try something new and unusual. My friend decided to please me and gave me a very tasty organic chocolate bar. If you also have a sweet tooth just go to the site https://chocolateandlove.com/products/sea-salt-57 and you can try this delicious food yourself.

답글 달기