计算R程序 [英] Computation R program
问题描述
我想计算出可能的最小数字,该数字可以被1到20的所有自然数均分.我已经用R语言编写了以下程序,但并没有获得所需的输出(相反,看来我的循环几乎永无止境).
I want to compute the smallest possible number that is divisible evenly by all the natural numbers from 1-20; I have written the following program in R and am not getting the desired output (rather it seems my loop is almost never ending).
我的程序如下:
a = 21
c = 0
while ( c < 20){
c = 0
n = 1
while ( n < 21 ){
if (a%%n == 0) c = c + 1
n = n+1
}
a = a + 1
}
print (a)
我哪里出错了?
推荐答案
这是一个更像R的解决方案,使用的事实是答案将是素数p <= 20
的乘积,每个素数均会升至索引i
,例如p^i <=20
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))
}
哪个产量:
> 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
虽然此解决方案很一般,但应注意,对于大的x
,isprime
是概率性的.当然,当这很可能会导致错误的结果时,您也可能会拥有一个太大的数字,以致于无法准确存储该数字.幸运的是,gmp包实现了一个大的整数类bigz
.若要将此更改用于函数的最后一行,请执行以下操作:
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)))
比较以下结果:
> sMult(1000)
[1] Inf
> sMult2(1000)
[1] "7128865274665093053166384155714272920668358861885893040452001991154324087581111499476444151913871586911717817019575256512980264067621009251465871004305131072686268143200196609974862745937188343705015434452523739745298963145674982128236956232823794011068809262317708861979540791247754558049326475737829923352751796735248042463638051137034331214781746850878453485678021888075373249921995672056932029099390891687487672697950931603520000"
这篇关于计算R程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!