Example #22: Fibonacci series in Scala This extends determine the nth fibonacci number using Scala. In this let’s print the Fibonacci series of length n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import scala.annotation.tailrec object Fibonacci extends App { val zero = BigInt(0) def fibTail(n: Long): BigInt = { if (n <= 1) return 1 @tailrec def fibRecursion(a: BigInt, b: BigInt, n: BigInt): BigInt = { n match { case `zero` => b //wrap with "`" to match against a variable case _ => fibRecursion(b, a + b, n - 1) } } fibRecursion(1, 1, n - 2) } def fibSeries(n: Long) = (1L to n).map (n => fibTail(n)) fibSeries(12).foreach {x => print(x + ", ") } } |
Output:
1 2 3 |
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, |
Q1 Is the above approach to “print the Fibonacci series of length…