Here's a more R-like solution using that fact that the answer will be the product of primes, p <= 20
, each raised to an index i
such that p^i <=20
sMult <- function(x)
# calculates smallest number that 1:x divides
{
v <- 1:x
require(gmp) # for isprime
primes <- v[as.logical(isprime(v))]
index <- floor(log(x)/log(primes))
prod(rep(primes,index))
}
Which yields:
> sMult(20)
[1] 232792560
> sMult(20)%%1:20
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
While this solution is general, it should be noted that for large x
, isprime
is probabalistic. Of course, when this is likely to give false results, you are also likely to have a number so large that it will not be able to be stored accurately. Fortunately the gmp package implements a large integer class, bigz
. To use this change to final line of the function to:
prod(as.bigz(rep(primes,index)))
Compare the following results:
> sMult(1000)
[1] Inf
> sMult2(1000)
[1] "7128865274665093053166384155714272920668358861885893040452001991154324087581111499476444151913871586911717817019575256512980264067621009251465871004305131072686268143200196609974862745937188343705015434452523739745298963145674982128236956232823794011068809262317708861979540791247754558049326475737829923352751796735248042463638051137034331214781746850878453485678021888075373249921995672056932029099390891687487672697950931603520000"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…