[英]how does modulus on a while loop executes?
I need help understanding this solution for getting a prime factor. 我需要帮助来了解此解决方案以获得主要因素。 this is the code demo
这是代码演示
function getMaxPrimeFactor (n) {
var temp = n;
for(var i = 2; i < temp; i++) {
while (temp % i === 0) {
temp /= i;
}
}
console.log(temp);
}
getMaxPrimeFactor(13195);
I understand the for loop but I don't know what's going on the while loop and the division, how did it get an output of 29? 我了解for循环,但不知道while循环和除法是怎么回事,它如何得到29的输出?
Here's what is going on: 这是怎么回事:
The point of the for
loop is to try every single divisor between 2 and the current value of temp
which starts out equal to the original number. for
循环的要点是尝试在2和temp
的当前值之间的每个除数开始,该temp
的当前值等于原始数。
The point of the while
loop is to take each one of those divisors and try them as many times as possible. while
循环的要点是采用每个除数并尝试尽可能多的除数。 As long as the remainder comes up 0
meaning it divided evenly, then keep dividing and reduce temp
to the result of the division each time. 只要余数达到
0
意味着它是均匀分配的,然后继续进行分配并将temp
降低到每次分配的结果。
So, while (temp % i === 0)
means to keep running the while loop as long as temp
divides by i
evenly with no remainder. 因此,
while (temp % i === 0)
意味着只要temp
除以i
且没有余数,就可以继续运行while循环。 The %
modulus operator computes the remainder after division. %
模运算符计算除法后的余数。
Here's a more instrumented version that when you run it shows you a bit more about what is going on: 这是一个更加实用的版本,在您运行时,它会告诉您更多有关发生的情况:
function getMaxPrimeFactor (n) { var temp = n; for(var i = 2; i < temp; i++) { while (temp % i === 0) { temp /= i; console.log("factor=",i,", ",temp*i,"/",i, "=",temp); } } console.log("remaining factor=",temp); } getMaxPrimeFactor(13195);
Here while
is checking if value of temp % i
is 0
(ie if temp
is divisible with i
). 在这里,
while
正在检查temp % i
值是否为0
(即temp
是否可被i
整除)。 If this condition is true
it will store temp / i
in temp
如果此条件为
true
,它将在temp
存储temp / i
So when the while
condition is true 所以当
while
条件成立时
i temp (temp % i) new_temp_value(temp/i)
5 13195 0 2639
7 2639 0 377
13 377 0 29
29 29 - - //for loop stops here since `i < temp` condition doesn't satisfy.
Last temp value is 29
上一个温度值为
29
So if we consider only i
value from above, we get 5, 7, 13, 29
which are factors of 13195
. 因此,如果仅考虑上面的
i
值,则得到13195
5, 7, 13, 29
这是13195
因数。
ie 5 * 7 * 13 * 29 = 13195
即
5 * 7 * 13 * 29 = 13195
So the max value in factors is 29
. 因此,因子的最大值为
29
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.