Recently, i have been indulging in a lot of codility challenges to improve my coding performance. For each of this exercise, I always aim for simple solutions as opposed to complicated ones that arrive at the same answer . The question is
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:
class Solution { public 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.
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))
I am aware a similar questions has been asked in java ChocolatesByNumbers but my question is more directed to C#
public static int PrintNChocolatesInaCircle(int N, int M)
{
int counter = 1;
int start = 0;
int value;
while ((start + M) % N != 0)
{
value = (start + M) % N;
start = value;
counter++;
}
return counter;
}
Codility scored my code in terms of Correctness 100% but in terms of performance, it takes longer time to process large elements e.g N = (3^9)(2^14), M=(2^14)(2^14) for a large element and going a bit higher the performance declines.
if (N == 0)
check, read the assumptions. \$\endgroup\$(start + M) % N
, store this somewhere in a variable and you'll likely see a large decrease in time taken. \$\endgroup\$