ChocolatesByNumber

There are n chocolates in a circle: count the number of chocolates you will eat
ℹ️ © Codility, 2009-2018

Problem

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 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.

Assume that:
n and m are integers within the range [1 … 1,000,000,000].

Complexity:
• expected worst-case time complexity is O(log(n + m));
* expected worst-case space complexity is O(log(n + m)).

Solution

C#

class Solution {
  public int solution(int n, int m) {
    return n / f(n, m);
  }
  private int f(int n, int m) {
    return n % m == 0 ? m : f(m, n % m);
  }
}

Java

class Solution {
  public int solution(int n, int m) {
    return n / f(n, m);
  }
  private int f(int n, int m) {
    return n % m == 0 ? m : f(m, n % m);
  }
}

JavaScript

function solution(n, m) {
  return n / f(n, m);
}
function f(n, m) {
  return n % m == 0 ? m : f(m, n % m);
}

PHP

function solution($n, $m) {
  return $n / f($n, $m);
}
function f($n, $m) {
  return $n % $m == 0 ? $m : f($m, $n % $m);
}