你好,斯塔克兰的好心人!
最近我被赋予了这个任务
我选择这样做,因为我正在学习语言,并认为这将是一个很好的练习。
我已经成功地完成了任务的第二步,但是已经无法继续下去了。请参阅下面的代码和评论。
len <- 50
fibvals <- numeric(len)
fibvals[1] <- 1
fibvals[2] <- 1
for(i in 3:len) { fibvals[i] <- fibvals[i-1]+fibvals[i-2]}
fibvals
[1] 1 1 2 3 5
[6] 8 13 21 34 55
[11] 89 144 233 377 610
[16] 987 1597 2584 4181 6765
[21] 10946 17711 28657 46368 75025
[26] 121393 196418 317811 514229 832040
[31] 1346269 2178309 3524578 5702887 9227465
[36] 14930352 24157817 39088169 63245986 102334155
[41] 165580141 267914296 433494437 701408733 1134903170
[46] 1836311903 2971215073 4807526976 7778742049 12586269025
# Creates a variable called len in which the value 50 is stored
# Creates a var called fibvals, which is a numeric datatype, which should have len (50) vals
# Sets the value of the first entry in fibvals to 1
# Sets the value of the second entry in fibvals to 1
# Loop - "for (i in 3:len)" dictates that the loop should be executed between step 3 and step 50 (denoted by "len")
# Loop - Defines a loop step "i" as being the result of the (current i - the before it) + (current i - i two before it)
# Loop - Example 5 = (5-3) + (5-2) OR 2 + 3 = 5 | Example 21 = (21-13) + (21-8) OR 8 + 13 = 21
is.even <- function(x){ x %% 2 == 0 }
# Creates a UDF to check if values are odd or even by using modulo.
If the remainder is 0 when any value is divided by 2, it is an even number
is.even(fibvals)
[1] FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE
[11] FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
[21] TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE
[31] FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE
[41] FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
# Evaluates all Fibonacci values on odd or even property我需要的是一点指导,说明我应该从这里走到哪里。我应该创建一个data.table并查询使用SQL,还是有一种更优雅、更不麻烦的方法?
提前感谢!
发布于 2016-07-02 16:45:20
为了从前50个斐波纳契数中筛选出偶数,可以使用以下方法
even_numbers <- fibvals[fibvals%%2==0]然后,通过计算这些偶数的累积和,并加上求和最大值的条件,您可以通过以下方法选择这些偶数。
cumsum(even_numbers)<500000因此,您想要的斐波纳契数是
even_numbers[cumsum(even_numbers)<500000]他们的sum是
sum(even_numbers[cumsum(even_numbers)<500000])发布于 2016-07-02 16:53:26
这样就行了
fsum <- 0
for (i in 1:len) { if (is.even(fibvals[i]) && (fsum + fibvals[i])<=500000) {fsum = fsum + fibvals[i]}}然后将该总和存储在fsum中。
发布于 2016-07-02 17:17:07
下面是一种使用递归函数来完成此操作的方法:
getEvenWithFibber <- function(y = c(1,1),
s = 0,
threshold = 500000) {
if(s + y[1] + y[2] < threshold)
getEvenWithFibber(y = c(y[1] + y[2],y), s = s + ifelse(y[1]%%2==0,y[1],0))
else list(sum = s, seq = y, iseven = y%%2 == 0)
}
getEvenWithFibber()https://stackoverflow.com/questions/38162209
复制相似问题