R
Ruby Newbie
I have the following assignment to be done.I have written the recursive
API and a loop based solution but what is the faster alternative for
these two that can figure into that "fastfunk(n)" method. Thanks for
your help in advance.
Funkonacci Numbers:
Define the Funkonacci numbers as follows:
0 if n < 1
funk(n) = 1 if n = 1
funk(n - 1) - (2 × funk(n - 2)) otherwise
Write a method funk(n) that calculates the nth Funkonacci number
recursively. Generate a few Funkonacci numbers. Now write a second
method, fastfunk(n) that calculates the nth Funkonacci number more
quickly
def funkn(n)
return 0 if n<=0
return 1 if n==1
funkn(n - 1) - (2 * funkn(n - 2))
end
def funknloop(n)
return 0 if n<=0
return 1 if n==1
i1 , i2 = 0,1
for i in 2...(n+1)
num = i2 - 2*i1
i1 ,i2 = i2, num
end
i2
end
puts funkn(10)
puts funknloop(10)
API and a loop based solution but what is the faster alternative for
these two that can figure into that "fastfunk(n)" method. Thanks for
your help in advance.
Funkonacci Numbers:
Define the Funkonacci numbers as follows:
0 if n < 1
funk(n) = 1 if n = 1
funk(n - 1) - (2 × funk(n - 2)) otherwise
Write a method funk(n) that calculates the nth Funkonacci number
recursively. Generate a few Funkonacci numbers. Now write a second
method, fastfunk(n) that calculates the nth Funkonacci number more
quickly
def funkn(n)
return 0 if n<=0
return 1 if n==1
funkn(n - 1) - (2 * funkn(n - 2))
end
def funknloop(n)
return 0 if n<=0
return 1 if n==1
i1 , i2 = 0,1
for i in 2...(n+1)
num = i2 - 2*i1
i1 ,i2 = i2, num
end
i2
end
puts funkn(10)
puts funknloop(10)