Java solution to Codility ChocolatesByNumbers problem (Lesson 12 – Euclidean algorithm) which scored 100%. The problem is to count the number of chocolates you will eat when there are N chocolates in a circle.
The strategy is to divide N by the greatest common divisor of N and M.
Reference
Solution to Chocolates-By-Numbers (Code Says)
1
2
3
4
5
6
7
8
9
10
11
12
13 package com.codility.lesson12.euclidean;
public class ChocolatesByNumbers {
public int solve(int N, int M) {
return N / gcdByDivision(N, M);
}
int gcdByDivision(int A, int B) {
if(A % B == 0) return B;
else return gcdByDivision(B, A % B);
}
}
TestNG test cases for this problem which all passed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 package test.com.codility.lesson12.euclidean;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.codility.lesson12.euclidean.ChocolatesByNumbers;
public class ChocolatesByNumbersTests {
private ChocolatesByNumbers solution;
@BeforeTest
public void setUp() {
solution = new ChocolatesByNumbers();
}
@DataProvider(name = "data1")
public Object [][] createData1() {
return new Object [][] {
new Object [] { 10, 4, 5 },
new Object [] { 10, 3, 10 },
new Object [] { 5, 6, 5 },
new Object [] { 5, 7, 5 },
new Object [] { 1, 1, 1 },
new Object [] { 2, 1, 2 },
new Object [] { 100, 1, 100 },
};
}
@Test(dataProvider = "data1")
public void verifySolution(int pN, int pM, int pExpected) {
Assert.assertEquals(solution.solve(pN, pM), pExpected);
}
}