Question

Restriction: No state is allowed in this question. Specifically, the keyword "var" is banned. (ie. You...

Restriction: No state is allowed in this question. Specifically, the keyword "var" is banned. (ie. You are expected to use a recursive solution)

Question: In a package named "functions" create an object named Numbers with a method named fib that: • Takes an Int as a parameter and returns the nth fibonacci number • Fibonacci numbers are equal to the sum of the previous two fibonacci numbers starting with 1 and 1 as the first two numbers in the sequence • Fibonacci numbers: 1, 1, 2, 3, 5, 8... • fib(1) == 1 • fib(2) == 1 • fib(3) == 2 • fib(4) == 3 • You method will not be tested with inputs < 1

Language: Scala

pls explain every steps thanks

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Scala is a functional programming language, so I will write and explain the Fibonacci function in Scala.

The following code snippet 'fib' is the Fibonacci recursive function. It has to be called from the main function with an integer as an argument.

def fib( n : Int) : Int = n match {
   case 0 | 1 => n
   case _ => fib( n-1 ) + fib( n-2 )
}

The code is explained below :

  1. The function fib takes integer n as an input.
  2. Then it enters a switch-case.
  3. For the 1st case, if the integer n is either 0 or 1, then it will return n.
  4. For the 2nd case if it is other than 0,1 then it will call the function fib again with (n-1) and (n-2) as arguments and return the sum of the fib function returns.
  5. The fib(n-1) and fib(n-2) are being called recursively with integer value n decremented by 1 and 2 respectively.
  6. This recursion call will continue until n becomes 0 or 1.
  7. And finally, it will return the n-th integer of the Fibonacci series.

The full code with the main function is attached below:

The main function calls the fib function with an integer value, let say 10, and it will return 55 as the 10th integer in Fibonacci series: 1 1 2 3 5 8 13 21 34 55.

Here is a small example of how the fib function works recursively with a small integer value, say 5.

I hope this will explain the code snippet of Fibonacci (recursion method), without using var.

Please leave a "Thumbs Up", it will be of great help. Thanks.

Happy Studying.

Add a comment
Know the answer?
Add Answer to:
Restriction: No state is allowed in this question. Specifically, the keyword "var" is banned. (ie. You...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT