一週間で身につくC# の勉強中12
prob8-10
1,1,2から始まり、前の3つの値の和を次の値とする数列のことを、トリボナッチ数列という(以下の例を参照)。このとき、30までのトリボナッチ数列を求めてint型の配列に代入し、表示しなさい。
例 1 1 2 4 7 13 24 …
考え方のポイント
長さ30の配列を作ります。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace prob8_10_2 { class Program { static void Main(string[] args) { int[] hi = new int[30]; hi[0] = 1; hi[1] = 1; hi[2] = 2; for (int i = 3; i < 30; i++) { int kazu = hi[i - 1] + hi[i - 2] + hi[i - 3]; hi[i] = kazu; } foreach (int i in hi) { Console.Write("{0} ", i); } } } }
数字が30までと考えて問題を解くと
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace prob8_10_2 { class Program { static void Main(string[] args) { int mae1 = 1; int mae2 = 1; int mae3 = 2; int kazu = 0; int count = 3; while (true) { kazu = mae1 + mae2 + mae3; if (kazu > 30) { break; } count++; mae1 = mae2; mae2 = mae3; mae3 = kazu; } mae1 = 1; mae2 = 1; mae3 = 2; int[] hi = new int[count]; hi[0] = 1; hi[1] = 1; hi[2] = 2; for(int i = 3; i < count; i++) { kazu = mae1 + mae2 + mae3; hi[i] = kazu; mae1 = mae2; mae2 = mae3; mae3 = kazu; } foreach(int i in hi) { Console.Write("{0} ", i); } } } }
一つ前の問題とは違い、無限ループを使っています。