Skip to content

Instantly share code, notes, and snippets.

@leemorgan
Last active February 22, 2024 21:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leemorgan/b26288e6909435c3193e to your computer and use it in GitHub Desktop.
Save leemorgan/b26288e6909435c3193e to your computer and use it in GitHub Desktop.
Fibonacci series in Swift
// Fibonacci series
// F[n] = F[n-1] + F[n-2]
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
// Find the fibonacci number for n interations
func fibonacci(n: Int) {
var num1 = 0
var num2 = 1
for _ in 0 ..< n {
let num = num1 + num2
num1 = num2
num2 = num
}
print("result = \(num2)")
}
fibonacci(7)
// Using Recursion
func fibonacciRecursiveNum1(num1: Int, num2: Int, steps: Int) {
if steps > 0 {
let newNum = num1 + num2
fibonacciRecursiveNum1(num2, num2: newNum, steps: steps-1)
}
else {
print("result = \(num2)")
}
}
fibonacciRecursiveNum1(0, num2: 1, steps: 7)
@dipoisola
Copy link

Why not:
func fibonacci(n: Int) -> Int { if n == 0 || n == 1 { return n; } else { return fibonacci(n: n - 1) + fibonacci(n: n - 2) } }

@gabrielPeart
Copy link

gabrielPeart commented Jun 8, 2017

or

func fibonacci(_ n: Int) -> Int {
    guard n != 0, n != 1 else { return n }
    return fibonacci(n - 1) + fibonacci(n - 2)
}

@arielelkin
Copy link

arielelkin commented Oct 9, 2017

// returns an array containing the first n Fibonacci numbers
func fibonacci(n: Int) -> [Int] {

    assert(n > 1)

    var array = [0, 1]

    while array.count < n {
        array.append(array[array.count - 1] + array[array.count - 2])
    }
    return array
}

fibonacci(n: 10) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

@prasad431
Copy link

@ALL @leemorgan Need to modify the code from your end what you wrote for Fibonacci

func fibonacci(n: Int) {

var num1 = 0
var num2 = 1

for _ in 0 ..< n {

    let num = num1 + num2
    num1 = num2
    num2 = num
}

print("result = \(num2)")

}

Above is exactly correct for Fibonacci Series of n-1 value

func fibonacci(n: Int) {

    var num1 = 0
    var num2 = 1
    
    for _ in 2...n {
        let num = num1 + num2
        num1 = num2
        num2 = num
    }
    
    print("result = \(num2)")
}

Above is exactly correct for Fibonacci Series of n value

Note::-- Fibonacci Series stats that except 0,1 in it so you need to start for loop from 2 onwards

@dimatarelkin
Copy link

func fib(_ n: Int) -> Int { return n < 2 ? n : (fib(n-1) + fib(n-2)) }

@sri12018
Copy link

sri12018 commented Dec 3, 2017

func fibonacciRecursiveNum1(num1: Int, num2: Int, steps: Int) {

if steps > 0 {
    let newNum = num1 + num2
    fibonacciRecursiveNum1(num2, num2: newNum, steps: steps-1)
}

@masiht
Copy link

masiht commented Jan 7, 2018

This is helpful, you can find all kinds of solutions for fibonacci in swift:
https://medium.com/@m.tabrizi/fibonacci-swift-playground-f56d1ff3ea99

@haashem
Copy link

haashem commented May 17, 2018

here you can find solution with description, I recommend to read:
https://www.weheartswift.com/recursion/

@freemansion
Copy link

freemansion commented May 26, 2018

one more quick implementation here:

func fib(_ num: Int) -> Int {
   switch num {
     case Int.min...1: return max(0, num)
     default: return fib(num-2) + fib(num-1)
   }
}

let sequence = Array(0...10)
sequence.forEach { print(fib($0)) } // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

@mime29
Copy link

mime29 commented Jan 23, 2019

careful for future readers, this iterative solution is wrong. f(0) should return 0, f(1) = 1, f(2) = 1

func fibonacci(n: Int) {

    var num1 = 0
    var num2 = 1

    for _ in 0 ..< n {
    
        let num = num1 + num2
        num1 = num2
        num2 = num
    }
    
    print("result = \(num2)")
}
fibonacci(7)

@abdurrahman-90
Copy link

func fibonacci(n : Int){
var n1 = 0
var n2 = 1

if n == 0 {
    
    print("invalid")
    
}else if n == 1 {
    
    print(n1)
    
}else if n == 2 {
    
    print(n1,n2)
    
}else {
    
    var array = [n1,n2]
    
    for _ in 2..<n{
        
        let n3 = n1 + n2
        
        n1=n2
        
        n2=n3
        
        array.append(n3)
        
        
    }
}

}
fibonacci(n: 10)

@NehaVaish
Copy link

careful for future readers, this iterative solution is wrong. f(0) should return 0, f(1) = 1, f(2) = 1

func fibonacci(n: Int) {

    var num1 = 0
    var num2 = 1

    for _ in 0 ..< n {
    
        let num = num1 + num2
        num1 = num2
        num2 = num
    }
    
    print("result = \(num2)")
}
fibonacci(7)

THIS CODE IS WRONG

@ferdinandu-creator
Copy link

func fibonaccin (n: Int) -> Array{

assert (n > 1)
var array = [0,1]

while array.count < n {
    array.append(array[array.count-1] + array[array.count-2])
    
    print(array)
}
return array

}
fibonaccin(n: 5)

@jibe0123
Copy link

func fib(_ n: Int) -> Int {
    guard n > 1 else { return n }
    return fib(n-1) + fib(n-2)
}

for x in 0...10 {
  print(fib(x))
}

@nicpro85
Copy link

nicpro85 commented Mar 21, 2022

Using decimal you can calculate to big number.

func fibonacci(n: Int) -> [Decimal] {
    
    if n == 0 {
        return [0]
    }
    if n == 1 {
        return [0,1]
    }
    var sequence: [Decimal] = [0,1]
    var num1: Decimal = 0
    var num2: Decimal = 1
    for _ in 2 ..< n+1 {
    
        let num : Decimal = num1 + num2
        num1 = num2
        num2 = num
        sequence.append(num)
    }
    return sequence
}
print("result = \(fibonacci(n: 120))")

@Sajjon
Copy link

Sajjon commented Nov 2, 2023

This is being a bit clever:

/// Generates a series of `numberOfElements` many fibonacci element, using recursion.
func fibonnaci(numberOfElements n: UInt) -> [Int] {
	let list = [0, 1]
	guard n > 2 else {
		return Array(list.prefix(Int(n)))
	}
	
	func inner(_ l: [Int]) -> [Int] {
		let m = l.count
		guard n != m else { return l }
		return inner(l + [(l[m - 2] + l[m - 1])])
	}
	
	return inner(list)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment