How to resolve the algorithm Fibonacci sequence step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Fibonacci sequence step by step in the Swift programming language

Table of Contents

Problem Statement

The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively:

Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: support for negative     n     in the solution is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Fibonacci sequence step by step in the Swift programming language

Source code in the swift programming language

import Cocoa

func fibonacci(n: Int) -> Int {
    let square_root_of_5 = sqrt(5.0)
    let p = (1 + square_root_of_5) / 2
    let q = 1 / p
    return Int((pow(p,CDouble(n)) + pow(q,CDouble(n))) / square_root_of_5 + 0.5)
}

for i in 1...30 {
    println(fibonacci(i))
}

func fibonacci(n: Int) -> Int {
    if n < 2 {
        return n
    }
    var fibPrev = 1
    var fib = 1
    for num in 2...n {
        (fibPrev, fib) = (fib, fib + fibPrev)
    }
    return fib
}

func fibonacci() -> SequenceOf<UInt> {
  return SequenceOf {() -> GeneratorOf<UInt> in
    var window: (UInt, UInt, UInt) = (0, 0, 1)
    return GeneratorOf {
      window = (window.1, window.2, window.1 + window.2)
      return window.0
    }
  }
}

func fibonacci(n: Int) -> Int {
    if n < 2 {
        return n
    } else {
        return fibonacci(n-1) + fibonacci(n-2)
    }
}

println(fibonacci(30))

  

You may also check:How to resolve the algorithm Pascal's triangle step by step in the ivy programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Visual Basic programming language
You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the Forth programming language
You may also check:How to resolve the algorithm McNuggets problem step by step in the MAD programming language
You may also check:How to resolve the algorithm Forest fire step by step in the Forth programming language