Skip to content

Instantly share code, notes, and snippets.

@TheMuellenator
Created April 20, 2021 15:07
Show Gist options
  • Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
class Assignment {
func fibonacci(n: Int) {
// Write your code here 👇
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)
}
print(array)
}
}
}
// Test your function here for different values of n 👇
let test = Assignment()
test.fibonacci(n: 11)
@ilyamfaisal28
Copy link

ilyamfaisal28 commented Feb 7, 2024

This is my solution

func fibonacci(n: Int) {

    var array: [Int] = []
    for i in 0..<n {
        if i == 0 || i == 1 {
            array.append(i)
        } else {
            array.append(array[i-2] + array[i-1])
        }
    }
    print(array)
}

@salanderm
Copy link

class Assignment {
var numbers = [0, 1]
var i: Int = 0
var number: Int = 0

func fibonacci(n: Int) {
    while (i < (n-2)) {
        number = numbers[i] + numbers[i + 1]
        numbers.append(number)
        i += 1
    }
print(numbers)
}

}

@vovahvfr
Copy link

vovahvfr commented Oct 24, 2024

class Assignment {
    func fibonacci(n: Int) -> Void {
        var sequence = [0, 1]
        for _ in 2..<n {
            sequence.append(sequence[sequence.count - 1] + sequence[sequence.count - 2])
        }
        print(Array(sequence.prefix(n)))
    }
}

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