Skip to content

Instantly share code, notes, and snippets.

@SatoTakeshiX
Created October 27, 2018 05:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SatoTakeshiX/22289c281658fe68ca040fe1efb7aef5 to your computer and use it in GitHub Desktop.
Save SatoTakeshiX/22289c281658fe68ca040fe1efb7aef5 to your computer and use it in GitHub Desktop.
フィボナッチ数列
// インデックス番号を入れたらその番号のフィボナッチ数を出力
func fib(index: Int) -> Int {
guard index > 1 else { return 1 }
var a = 1
var b = 1
(2...index).forEach { (index) in
(a, b) = (a + b, a)
}
return a
}
(0...10).forEach { (index) in
print(fib5(index: index))
}
//出力
//1
//1
//2
//3
//5
//8
//13
//21
//34
//55
//89
// インデックス番号を入れたらそれまでのフィボナッチ数列を出力
func fibSequence(index: Int) {
guard index > 1 else {
print("1")
return
}
var fibArray = [1, 1]
(2...index).forEach { (index) in
fibArray.append(fibArray[index-2] + fibArray[index-1])
}
let sequence = fibArray.reduce("") { (result, value) -> String in
if result.isEmpty {
return "\(value)"
} else {
return "\(result),\(value)"
}
}
print(sequence)
}
fibSequence(index: 16)
// -> 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment