Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Function that finds the n number in the fibonacci sequence
- // Takes 1 parameter (desired element's order number in the sequence)
- // Returns 1 value (desired element's value)
- // Bonus: works with negative numbers
- /*
- 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
- */
- /*
- def recursiveFib(n: Long): Long ={
- if (n <= 1)
- n
- else
- recursiveFib(n-1) + recursiveFib(n-2)
- }
- */
- def recursiveFib(n: Long): Long ={
- if (n == 0 || n == 1)
- n
- else if (n < 0)
- recursiveFib(n+2) - recursiveFib(n+1)
- else
- recursiveFib(n-1) + recursiveFib(n-2)
- }
- println("Recursive function with 0, 1, 10, 7, 13, -6")
- recursiveFib(0)
- recursiveFib(1)
- recursiveFib(7)
- recursiveFib(10)
- recursiveFib(13)
- recursiveFib(-6)
- def tailRecursiveFib(n: Long): Long ={
- def rec(counter:Long, resultOne:Long, resultTwo:Long):Long={
- //println(s"$counter | $resultOne $resultTwo\n")
- if (counter <= 1)
- resultTwo
- else
- rec(counter-1, resultTwo, resultOne+resultTwo)
- }
- rec(n, 0, 1)
- }
- println("Tail recursive function with 0, 1, 10, 7, 13")
- tailRecursiveFib(0)
- tailRecursiveFib(1)
- tailRecursiveFib(7)
- tailRecursiveFib(10)
- tailRecursiveFib(13)
- def imperativeFib(n: Long): Long ={
- if (n == 0) n
- else{
- var counter = n
- var first = 0L
- var second = 1L
- var result = 1L
- while (counter >= 2){
- //println(s"$counter | $first $second | $result\n")
- result = first + second
- first = second
- second = result
- counter -= 1
- }
- result
- }
- }
- println("Imperative function with 0, 1, 10, 7, 13")
- imperativeFib(0)
- imperativeFib(1)
- imperativeFib(7)
- imperativeFib(10)
- imperativeFib(13)
- def fib(n: Long): Long={
- ((scala.math.pow(1.618034, n) - scala.math.pow(-0.618034, n))/scala.math.sqrt(5)).toLong
- }
- println("Mathematical function using the Golden Ratio with 0, 1, 10, 7, 13")
- fib(0)
- fib(1)
- fib(7)
- fib(10)
- fib(13)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement