R studio for loop fibonacci11/24/2023 ![]() Comparing the speed of the recursive function and the loop function So, let’s compare the speed of the 2 function: recursiveFib and loopFib. Notice that calling recursiveFib(30) took some time to run. # making the function recursiveFib accept vector inputs } Testing the function recursiveFib: recursiveFib(1) # outputs: 1 RecursiveFib(n - 1) + recursiveFib(n - 2) # by calling the current function on n-1 and n-2 # else, return the sum of the previous 2 numbers Writing a Fibonacci function using recursion # Fibonacci function using recursion ![]() # this is simpler than entering each input separately ![]() # making the function loopFib accept vector inputs # print the first 10 numbers of the Fibonacci sequence } Testing the function loopFib: loopFib(1) # outputs: 1 # each number is the sum of the 2 preceding onesįibSeq = fibSeq + fibSeq # fill the rest of the sequence for n > 2 Writing a Fibonacci function using a for loop # Fibonacci function using a for loop Then, we will compare the runtime of the 2 solutions, and provide a trick to speed up the slower one. And the other by writing the function using recursion.One by writing the function using for loop.In this article, I will present 2 solutions: So, the first Fibonacci number is 1, the second is also 1, and then each subsequent number is the sum of the previous 2 in the sequence. Reminder: the Fibonacci sequence is: 1, 1, 2, 3, 5, 8, … Write a function in R that prints the n th Fibonacci number.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |