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?

More than 1 year has passed since last update.

トリボナッチ数列&テトラナッチ数列(PHP)

Posted at

トリボナッチ数列・・・自身の前の3つの数字を足した数列。
テトラナッチ数列・・・自身の前の4つの数字を足した数列。

<?php
//20個のトリボナッチ数列を求める

//求める個数
$number=20;

//トリボナッチ数列を求める関数
function tribo($num) {
    if($num==0){
        return 0;
    }
    if($num==1){
        return 0;
    }
    if($num==2){
        return 1;
    }
    $tri=0; 
    $tri_0=0;
    $tri_1=0;
    $tri_2=1;
    for($i=3;$i<=$num;$i++) {
        //トリボナッチ数を求める
        $tri=$tri_0+$tri_1+$tri_2;
        //各々の数の更新
        $tri_0=$tri_1;
        $tri_1=$tri_2;
        $tri_2=$tri;
    }
   return $tri;
}

//結果の表示 	
for($i=0;$i<=$number;$i++) {
    echo ($i.": ".tribo($i))."\n";
}
?>

結果

0: 0
1: 0
2: 1
3: 1
4: 2
5: 4
6: 7
7: 13
8: 24
9: 44
10: 81
11: 149
12: 274
13: 504
14: 927
15: 1705
16: 3136
17: 5768
18: 10609
19: 19513
20: 35890
<?php
//20個のテトラナッチ数列を求める

//求める個数
$number=20;

//テトラナッチ数列を求める関数
function tetra($num) {
    if($num==0){
        return 0;
    }
    if($num==1){
        return 0;
    }
    if($num==2){
        return 0;
    }
    if($num==3){
        return 1;
    }
        
    $tet=0; 
    $tet_0=0;
    $tet_1=0;
    $tet_2=0;
    $tet_3=1;
        
    for ($i=4;$i<=$num;$i++) {
        //テトラナッチ数を求める
        $tet=$tet_0+$tet_1+$tet_2+$tet_3;
        
        //各々の数の更新
        $tet_0=$tet_1;
        $tet_1=$tet_2;
        $tet_2=$tet_3;
        $tet_3=$tet;
    }
    return $tet;
}

//結果の表示 	
for($i=0;$i<=$number;$i++) {
    echo ($i.": ".tetra($i))."\n";
}
?>

結果

0: 0
1: 0
2: 0
3: 1
4: 1
5: 2
6: 4
7: 8
8: 15
9: 29
10: 56
11: 108
12: 208
13: 401
14: 773
15: 1490
16: 2872
17: 5536
18: 10671
19: 20569
20: 39648

なんかもっと簡略化できる気もする。

0
0
2

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?