본문 바로가기
SW/알고리즘 문제풀이

[Codility] Lesson12 - euclidean algorithm: Chocolates By Numbers

by 미래미래로 2021. 2. 8.
728x90

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/

 

ChocolatesByNumbers coding task - Learn to Code - Codility

There are N chocolates in a circle. Count the number of chocolates you will eat.

app.codility.com

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/

 

Test results - Codility

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 num

app.codility.com

 

728x90

댓글