Below is my solution for finding the number of trailing zeros in a factorial, it works, i'm posting it to give an idea of how the algorithm works which is the sum of quotients of n divided by 5 ^ i, where i>0.
#include <cmath>
long zeros(long n) {
long sum = 0;
for (int i = 1;; ++i) {
int m = n / pow(5, i);
if (m == 0)
break;
else sum += m;
}
return sum;
}
I saw this solution which confused me with its use of the =
operator. What does =5
mean in this context?
long zeros(long n) {
long result = 0;
while(n)
result += n/=5;
return result;
}
The expression result += n/=5
is equivalent to first updating the value of n
to n/5
and then updating the value of result
to result + n
where n
is now n/5
.
// result += n/=5 is same as doing
n = n / 5;
result = result + n;
Here the /=
is analogous to +=
in the sense that n/=5
is equivalent to n = n/5
将值或变量分配给变量,即 m = n 表示如果 n 为 15,则 m 将是 n 的值,即 15
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.