简体   繁体   中英

Use for and while to express factorial in r

在此处输入图片说明

1+(2+1/2!)+(3+1/3!)......+(20+1/20!)

-only use for or while

    sum=0.0
sub_sum=0.0
i=2
j=20
while(i<=20){
  print(i)
  sub_sum=1.0
  j=1.0
  while(j<=i){
    print("j")
    print(j)
    print("sub_sum")
    print(sub_sum)
    sub_sum=j+sub_sum*(1/j)
    j=j+1
  }
  sub=sum+sub_sum
  i=i+1
}
print(sum)

but I've tried it over and over again using while, but it keeps getting the wrong price.

With n=20

sapply(1:n, function(x) x+1/factorial(x)) %>% sum - 1

or

sapply(1:n, function(x) x+1/prod(1:x)) %>% sum - 1

With res = -1

(1) for-loop :

tmp = 1
for (i in 1:n) {
  tmp = tmp * i
  res = res + i + 1/tmp
}
res

(2) while loop :

tmp = 1
i = 1
while (i <= n) {
  tmp = tmp * i
  res = res + i + 1/tmp
  i = i + 1
}
res

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM