zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    在linux上通过docker运行容器,通过docker搭建jenkens环境
    linux jdk 安装报错
    UEditor 后台配置项返回格式出错,上传功能将不能正常使用!
    spring boot 项目 freemarker 无法加载static 中 js css 文件 原因(报错404)
    windows mongodb 添加用户
    window连接本地mongodb 报错 mongodb shell was not initiallized
    Zookeeper(四) 客户端shell命令
    Zookeeper(三) 集群搭建
    Zookeeper(二) 安装及配置
    Zookeeper(一) 入门
  • 原文地址:https://www.cnblogs.com/hiluna/p/8855055.html
Copyright © 2011-2022 走看看