I was trying to calculate the number of trailing zeros in a factorial of a given number, eg,
6!=720
, which has 1
trailing zero 10!=3628800
, which has 2
trailing zeros My question, I have a data frame like df <- data.frame(n=1:50)
, how could I add another column which gives the number of trailing zeros, eg,
n trail0s
1 1 0
2 2 0
3 3 0
4 4 0
5 5 1
6 6 1
7 7 1
8 8 1
9 9 1
10 10 2
...
I know factorial
in R is to calculate factorial, but I have no idea how to count the trailing zeros. Any help would be appreciated!
I think you should apply some mathematical properties of factorial
before counting the number of trailing zeros, see https://mathworld.wolfram.com/Factorial.html
In factorial(n)
, you should know that the number of trailing zeros depends on the pairs of 2*5
in the cascaded product 1*2*...*n
. In this case, you can define your custom function zeros
like below
zeros <- Vectorize(function(n) ifelse(n>=5,sum(sapply(seq_along(floor(logb(n,5))), function(p) floor(n/5**p) )),0))
then you can add the column of trailing zeros via
df <- within(df,trail0s <- zeros(n))
such that
> df
n trail0s
1 1 0
2 2 0
3 3 0
4 4 0
5 5 1
6 6 1
7 7 1
8 8 1
9 9 1
10 10 2
11 11 2
12 12 2
13 13 2
14 14 2
15 15 3
16 16 3
17 17 3
18 18 3
19 19 3
20 20 4
21 21 4
22 22 4
23 23 4
24 24 4
25 25 5
26 26 5
27 27 5
28 28 5
29 29 5
30 30 6
31 31 6
32 32 6
33 33 6
34 34 6
35 35 7
36 36 7
37 37 7
38 38 7
39 39 7
40 40 8
41 41 8
42 42 8
43 43 8
44 44 8
45 45 9
46 46 9
47 47 9
48 48 9
49 49 9
50 50 10
> library(stringi)
> x1<- c(1:7)
> x2 <- c(10,20,200,220, 50,300,7000)
> df<- data.frame(x1,x2)
> df$x0trail <- stri_count(df$x2, regex="0")
> df
x1 x2 x0trail
1 1 10 1
2 2 20 1
3 3 200 2
4 4 220 1
5 5 50 1
6 6 300 2
7 7 7000 3
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.