ChocolatesByNumbers – Codility – Solution

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)

[cc lang="java" escaped="true"]
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);
	}
	
}
[/cc]

TestNG test cases for this problem which all passed:

[cc lang="java" escaped="true"]
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);		
	}
}
[/cc]