Contents
How do you write Fibonacci series in Scala?
Fibonacci numbers in Scala This example uses recursive definition of Fibonacci numbers. object Fibonacci { def fibonacci(n: Int): Int = if (n < 3) 1 else fibonacci(n – 1) + fibonacci(n – 2) def main(args: Array[String]) { for {i <- List. range(1, 17)} yield { print(fibonacci(i) + “, “) } println(“…”) } }
What is Fibonacci series in Scala?
Today, I spent some time to experiment with various ways to calculate Fibonacci numbers in Scala. Scala is a functional programming language, so the first version uses recursion: 1 2 3 4. def fib1( n : Int) : Int = n match { case 0 | 1 => n case _ => fib1( n-1 ) + fib1( n-2 ) }
How do you find prime numbers in Scala?
exists(x => i % x == 0) | } // isPrime2: (i: Int)Boolean (1 to 10). foreach(i => if (isPrime2(i)) println(“%d is prime.”. format(i))) // 2 is prime. // 3 is prime. // 5 is prime. // 7 is prime. Which also returns a Boolean.
How do you write a factorial function Scala?
Scala – Recursion Functions
- Example. object Demo { def main(args: Array[String]) { for (i <- 1 to 10) println( “Factorial of ” + i + “: = ” + factorial(i) ) } def factorial(n: BigInt): BigInt = { if (n <= 1) 1 else n * factorial(n – 1) } }
- Command. \>scalac Demo.scala \>scala Demo.
- Output.
What do rabbits do with Fibonacci?
Fibonacci considers the growth of an idealized (biologically unrealistic) rabbit population, assuming that:
- a single newly born pair of rabbits (one male, one female) are put in a field;
- rabbits are able to mate at the age of one month so that at the end of its second month a female can produce another pair of rabbits;
Is prime function in Scala?
Since you are working with the REPL, you would want to define your function to check if a number is prime. I called it isPrime2 and then test it. def isPrime2(i :Int) : Boolean = { | if (i <= 1) | false | else if (i == 2) | true | else | !( format(i))) // 2 is prime. // 3 is prime. // 5 is prime. // 7 is prime.