Two Joggers ( 5 kyu )

문제

Your job is to complete the function nbrOfLaps(x, y) that, given the length of the laps for Bob and Charles, finds the number of laps that each jogger has to complete before they meet each other again, at the same time, at the start.

The function takes two arguments:

  1. The length of Bob’s lap (larger than 0)
  2. The length of Charles’ lap (larger than 0)

The function should return an array (Tuple in C#) containing exactly two numbers:

  1. The first number is the number of laps that Bob has to run
  2. The second number is the number of laps that Charles has to run

Examples:

nbrOfLaps(5, 3); // returns [3, 5]
nbrOfLaps(4, 6); // returns [3, 2

두 명이 서로 다른 원형 트랙을 돌면서 시작점에서 다시 만날때까지 몇바퀴를 돌아야 하는지 찾는 문제

풀이

var nbrOfLaps = function (x, y) {
  let gcd = 1;
  for ( let i = 2; i <= Math.min(x,y); i++ ) {
    if ( x % i === 0 && y % i === 0 ) {
      gcd = i;
    }
  }
  return [y/gcd, x/gcd];
}

gcd 즉 최대 공약수를 구하는 문제

약간의 연산을 더해 결과값 리턴

다른 사람의 풀이

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

var nbrOfLaps = function (x, y) {
  var lcm = (x*y)/ gcd(x,y);
  return [lcm/x, lcm/y];
}

유클리드 호제법 사용.

내가 짠 코드보다 훨씬 실행시간이 줄어들음


+ Recent posts