codewars--js--Two Joggers--求最小公倍数、最大公约数

问题描述:

Two Joggers

Description

Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed.

Illustration

Example where Charles (dashed line) runs a shorter lap than Bob:

Example laps

Task

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<int, int> 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]


解题思路: 很明显就是先求这两个数的最小公倍数,然后再分别除以Bob、Charles的长度,即可得他们俩分别的圈数。

lcm:最小公倍数,a*b/gcd

gcd:最大公约数(greatest common divisor,简写为gcd;可用辗转相除法得到

我的答案:

 1 var nbrOfLaps = function (x, y) {
 2   var a=gcd(x,y);
 3   var b=y/a;
 4   var c=x/a;
 5   return [b, c];
 6 }
 7 
 8 function gcd(a,b){
 9 var temp;
10   if(a<b){temp=a;a=b;b=temp;}
11   while(b!=0){
12     temp=a%b;
13     a=b;
14     b=temp;    
15   }
16   return a;  
17 }

 

优秀答案:

(1)

1 var nbrOfLaps = function(x, y) {
2   var lcm = x;
3   while(lcm % y != 0) {lcm += x;}
4   return [lcm / x, lcm / y];
5 } 

(2)

 

 

 1 function gcd(a, b) {
 2   if(b == 0)
 3     return a;
 4   return gcd(b, a % b);
 5 }
 6 
 7 var nbrOfLaps = function (x, y) {
 8   var lcm = (x*y)/ gcd(x,y);
 9   return [lcm/x, lcm/y];
10 }

转载于:https://www.cnblogs.com/hiluna/p/8855055.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值