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 }
  • 相关阅读:
    CCF 认证
    ZOJ Light Bulb
    codeforce 605BE. Freelancer's Dreams
    HDU2546——背包DP——饭卡
    转载DD大神背包九讲
    背包九讲
    zstu4186——线段树——表白计划(未完成)
    zstu4189——后缀表达式——逻辑运算
    蛇形矩阵
    zs深入浅出学算法022——DFS———汉诺塔问题II
  • 原文地址:https://www.cnblogs.com/hiluna/p/8855055.html
Copyright © 2011-2022 走看看