Problem
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:
int solution(int N, int 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.
Write an efficient algorithm for the following assumptions:
- N and M are integers within the range [1..1,000,000,000].
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/
How to solve
처음에는 chocolate flag 배열을 만들어서 먹은 초콜렛을 check해주었는데, timeout
N과 M의 최소 공약수를 gcd를 구하고,
1) 0 => 1개
2) 0< < N-1 사이에서 최소공약수의 배수의 갯수 => N/gcd - 1
즉, 1 + (N/gcd - 1) = N/gcd
Solution(c++)
// you can use includes, for example:
#include <bits/stdc++.h>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int calc_gcd(int a, int b){
if(b == 0){
return a;
}else{
return calc_gcd(b, a%b);
}
}
int solution(int N, int M) {
// write your code in C++14 (g++ 6.2.0)
int gcd = calc_gcd(N, M);
int res = N/gcd;
return res;
}
Test Result
app.codility.com/demo/results/trainingTACFMS-K6A/
'SW > 알고리즘 문제풀이' 카테고리의 다른 글
[Codility] Lesson16 - Greedy algorithms: Max Nonoverlapping Segments (1) | 2021.02.10 |
---|---|
[Codility] Lesson12 - Euclidean algorithm: Common Prime Divisors (0) | 2021.02.09 |
[Codility] Lesson10 - Prime and composite numbers: MinPerimeterRectangle (1) | 2021.01.30 |
[Atcoder] D - Friends (C++) (1) | 2021.01.13 |
[Codility] Lesson10 - Prime and Composite numbers : CountFactors (c++) (1) | 2021.01.12 |
댓글