Search code examples
rlcm

Pracma::Lcm() only returns NA in loop


I am trying to obtain the least common multiplier of the prime numbers in between 1 and 20:

x <- expand.grid(c(2,3,7,11,13,17,19),c(2,3,7,11,13,17,19))
l <- c()
# loop
for(i in length(x[,1])){
l[i] <- pracma::Lcm(x[i, 1], x[i, 2])
}
# gives
tail(l)
[1] NA NA NA NA NA 19

Interestingly, the loop returns only NA's besides the first and last value, this doesn't make sense since one can obtain the values by hand:

pracma::Lcm(x[4, 1], x[4, 2])
[1] 22

Can anyone spot what I am missing?

Thank you in advance!


Solution

  • We can initiate l with instead of c(). Also, length is a single value. We need seq_len(nrow(x))

    l <- numeric(nrow(x))
    
    for(i in seq_len(nrow(x))) {
         l[i] <- pracma::Lcm(x[i, 1], x[i, 2])
     }
    
    l
    #[1]   2   6  14  22  26  34  38   6   3  21  33  39  51  57  14  21   7  77  91 119 133  22  33  77  11 143 187 209  26  39  91 143  13
    #[34] 221 247  34  51 119 187 221  17 323  38  57 133 209 247 323  19
    

    If we initiate as c(), then inside the loop, it would be

     l <- c(l, pracma::Lcm(x[i, 1], x[i, 2]))
    

    Also, the pracma::Lcm is vectorized, so no need to loop over each rows

    pracma::Lcm(x[,1], x[,2])
    #[1]   2   6  14  22  26  34  38   6   3  21  33  39  51  57  14  21   7  77  91 119 133  22  33  77  11 143 187 209  26  39  91 143  13
    #[34] 221 247  34  51 119 187 221  17 323  38  57 133 209 247 323  19
    

    In the OP's code, the

    length(x[,1])
    #[1] 49
    

    is a single number i.e. the last row, here, i.e. only looping through that last row

    Second issue is during the assignment, where we assign with a length of 0 and when we use index, it is creating a NULL

    l <- c()
    length(l)
    #[1] 0
    l[1]
    #NULL