查找最小倍数
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>
编辑:请考虑在发布前缩进您的代码。此外,作为编程的一般规则,最好以唤起它们应该做的事情的方式命名函数。并使变量的范围尽可能小。:)
相关文章:
- 正在全局范围中查找JavaScript函数
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在不使用jquery的情况下查找页面中的所有锚点并附加函数
- es6 相当于下划线查找位置
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何在不传递此信息的情况下查找被调用的元素
- Lodash 从值数组中查找数组中的值
- 如何使用JavaScript查找1和N之间的所有数字的总和
- 使用RegExp查找url中的字符
- 查找元素高度,包括边距
- 使用JS查找数组的平均值
- 查找最短和最长日期
- 猫鼬在特定记录中查找嵌套记录
- 使用javascript在MVC中查找网格长度时出错
- 在Javascript数组中查找绝对最大值
- 在javascript中查找单词
- JavaScript 在数组中查找缺少的数字
- 键按正则表达式以查找具有负值的小数
- 为什么可以't Protractor在自动初始化的Angular网站上查找Angular