0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinでループ処理を使ってトリボナッチ数を求める

Last updated at Posted at 2022-10-08

トリボナッチ数とは

トリボナッチ数とは、下記定義によって表される数列または数である。フィボナッチ数と関係が深い。
F0 = 0
F1 = 0
F2 = 1
Fn+3 = Fn + Fn+1 + Fn+2

引用 Numberpedia様より

求め方

for文使って、代入を繰り返せば実装できます。

コード

fun main(args: Array<String>) {
    val num:Int
    for(i in 0..50) {
        print("${i}:${calc(i)}\n")
    }
}

fun calc(num : Int):Int {
    var first = 0
    var second = 1
    var third = 1
    return when (num) {
        0 -> 0
        1 -> first
        2 -> second
        3 -> third
        else -> {
            var current = first + second + third
            for (i in 4..num) {
                current = first + second + third
                first = second
                second = third
                third = current
            }
            current
        }
    }
}

結果

0:0
1:0
2:1
3:1
4:2
5:4
6:7
7:13
8:24
9:44
10:81
...

追記

再起的に関数を呼び出したバージョン。
こちらの方が記述量が少なくスッキリ書けます。

/*
再起関数を改良したバージョン
*/
fun main(args: Array<String>) {
    val num:Long = 50
    for(i in 0..num) {
        print("${i}:${fibonacci(i)}\n")
    }
}

fun fibonacci(num: Long):Long {
    return fib2(0, 1, num)
}

fun fib2(a:Long,b: Long,c:Long):Long{
    if(c < 1) {
        return a;
    }
    return fib2(a + b, a, c - 1)
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?