Numbers

From Codility

The GCD is most often calculated for two numbers, when it is used to reduce fractions to their lowest terms. When the greatest common divisor of two numbers is 1, the two numbers are said to be coprime or relatively prime.

Example:
console.log(solution(10,4)); => 5
console.log(solution(9,6)); => 3
console.log(solution(10,11)); => 10

function findGcd(a, b) {
  if (b === 0) {
    return a;
  } else {
    return findGcd(b, a%b);
  }
}

function solution(N, M) {
  return N / findGcd(N,M);
}

console.log(solution(10,4)); => 5
console.log(solution(9,6)); => 3
console.log(solution(10,11)); => 10


We create a function called findGcd with parameters called a, b.

We us the if statement to check if ( b === 0) if it is we return a
Else we return findGcd function and inside parameters return findGcd(b, a % b);

We create the main function called solution with parameters N and M and simply we return N / findGcd(N, M);

So to print the values we use console.log build in function console.log(solution(10,4)); and it returns 5

comments powered by Disqus