查找最小倍数

Finding the smallest multiple

本文关键字:查找      更新时间:2023-09-26

我正在尝试自己学习和练习javascript,我已经取得了一些进步,但我仍然会遇到基本问题。 我认为我的代码非常接近给我正确的答案,但我看不到我错过了什么问题。 如果有人更擅长编码,请花点时间告诉我我有什么逻辑错误,我将不胜感激!

<script>
//2520 is the smallest number that can be divided by each of the numbers from 1 to         10 without any remainder.
var input = 11;
function smallestMultiple(){
    for(var i = 2; i <= 10; i++){
        if(input % i === 0 && isDivisible(input))
            alert(input);//this should only alert when input is divisible by all numbers between 2 and 10   
        }else{
            input ++;
//if input isn't divisible by all numbers between 2 and 10, increment input by 1        
        }
    }
};
// The following function should return true when "input" is divisible by 10, which is the trigger for alerting "input"
function isDivisible(input){
    if(input % 10 === 0){
        return true;
    }else{
        return false;
    }
};
smallestMultiple();

</script>

您的脚本将找到可被 10 整除的最小整数和 2,3,...,9 中的数字,这不是您需要的。

更快的实现可能是设置几个临时除数,这些除数会缩小,直到左边缘超过右边缘......

最简单的方法是在1,2,3...,9中选择一个数字,然后尝试将其除以1,2,3...,9中的每个数字

以下 html 沙箱(保持主题(可能会帮助您理解。

<html>
<head>
    <meta charset="utf8">
</head>
<body>
    <div>
        <p class="output"></p>
    </div>
    <script>
    window.onload = function() {
        function smallest_shared_multiple(from, to) {
            var tmp_divisor = from
            var tmp_candidate = tmp_divisor
            for(;tmp_divisor < to +1;) {
                if (tmp_candidate % tmp_divisor) {
                    tmp_divisor = from
                    tmp_candidate++
                } else {
                    tmp_divisor++
                }
            }
            return tmp_candidate                                       
        }
        document.querySelector('p.output').innerHTML =
            'For the given range, the smallest shared multiple is ' +
            smallest_shared_multiple(1, 10)
    }
    </script>
</body>
</html>

编辑:请考虑在发布前缩进您的代码。此外,作为编程的一般规则,最好以唤起它们应该做的事情的方式命名函数。并使变量的范围尽可能小。:)