【问题标题】:Find the smallest common multiple求最小公倍数
【发布时间】:2020-07-11 06:48:25
【问题描述】:

我希望你能理解我。我想得到我给函数的数字范围之间的最小公倍数,例如,如果我把looker(1,3)函数将在1,2,3中寻找最小的公倍数,这就是范围,答案是6,我不知道是否得到它。 这是来自freecodecamp的挑战,问题在于当我使用范围(1,3)运行函数时,它可以工作,(1,5)它可以工作,但是对于其他范围,谷歌控制台会显示“rende process gone”。

const looker = (arra) => {
var nume = [];
var status = "no";
var statusN = 0;
var array = [];
var mul = [];
var contador = arra[1];
var aumentador = 2;

while(contador > arra[0] - 1) {
    array.push(contador);
    mul.push(contador);
    nume.push(contador);
    contador--;
}
// console.log(nume);
// console.log(array);
// console.log(mul);
// console.log(contador);

while(contador != arra[1]) {
    for(let x of nume) {
        array.push(x*aumentador);
        mul.push(x*aumentador);
    }
    aumentador++;

    for(let a of mul) {
        for(let i of array) {
            if(a == i) {
                contador++;
            }
        }

        if(contador == arra[1]) {
            status = "si"
            statusN = a;
            break;
        } else {
            status = "no";
            contador = 0;
        }
    }
}

if(status == "si") {
    console.log(`el numero que se repite es ${statusN}`);
} else {
    console.log(`ningun numero se repite ${arra[1]} veces`);
}   

}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    我想你想要这样的东西..

    function findGCD() {
      if($("#first").val() != null && $("#second").val() != null ){
        let fn = parseInt($("#first").val());
        let sn = parseInt($("#second").val());
        let gcd = lcm_two_numbers(fn, sn);
        $("#answer").html("Smallest common multiple : " + gcd)
      }
    }
    
    function lcm_two_numbers(x, y) {
       if ((typeof x !== 'number') || (typeof y !== 'number')) 
        return false;
      return (!x || !y) ? 0 : Math.abs((x * y) / gcd_two_numbers(x, y));
    }
    
    function gcd_two_numbers(x, y) {
      x = Math.abs(x);
      y = Math.abs(y);
      while(y) {
        var t = y;
        y = x % y;
        x = t;
      }
      return x;
    }
    button {
      background: #0095ff;
      padding: 8px;
      border-radius: 3px;
      border: none;
      color: white;
      width: 80px;
      margin-left: 20px;
      cursor: pointer;
    }
    
    p {
     font-weight: 700;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label for="first">First number:</label>
    <input type="number" id="first" name="first" min="1" max="5">
    <label for="second">Second number:</label>
    <input type="number" id="second" name="second" min="1" max="5">
    <button  onclick="findGCD()">GCD</button>
    <p id="answer"></p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-16
      • 2020-10-12
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 2020-09-05
      相关资源
      最近更新 更多