| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

アルゴリズム C Sharp 漸化式

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

アルゴリズム C# 漸化式

コード

class Combination
{
    /// <summary>
    /// 漸化式 (nCr) の計算
    /// </summary>
    /// <param name="n"></param>
    /// <param name="r"></param>
    /// <returns></returns>
    public static long Combi(int n, int r)
    {
        long p = 1;

        for (int i = 1; i <= r; i++)
        {
            p = p * (n - i + 1) / i;
        }
        return p;
    }
    public static void SampleCombi()
    {
        for (int n = 0; n <= 5; n++)
        {
            for (int r = 0; r <= n; r++)
            {
                Console.Write($"{n}C{r} = {Combi(n, r)}  ");
            }
            Console.Write("\n");
        }
    }

    /// <summary>
    /// Hornerの方法
    /// </summary>
    /// <param name="x"></param>
    /// <param name="a"></param>
    /// <param name="n"></param>
    /// <returns></returns>
    public static double Horner(double x, double[] a, int n)
    {
        double p = a[n];
        for (int i=n-1; i>=0; i--)
        {
            p = p * x + a[i];
        }
        return p;
    }
    public static void SampleHorner()
    {
        double[] a = { 1, 2, 3, 4, 5 };
        for(double x=1; x<=5; x++)
        {
            Console.WriteLine($"fn({x:#0.000}) = {Horner(x,a,4):#0.000}");
        }
    }
}

結果

0C0 = 1
1C0 = 1  1C1 = 1
2C0 = 1  2C1 = 2  2C2 = 1
3C0 = 1  3C1 = 3  3C2 = 3  3C3 = 1
4C0 = 1  4C1 = 4  4C2 = 6  4C3 = 4  4C4 = 1
5C0 = 1  5C1 = 5  5C2 = 10  5C3 = 10  5C4 = 5  5C5 = 1

fn(1.000) = 15.000
fn(2.000) = 129.000
fn(3.000) = 547.000
fn(4.000) = 1593.000
fn(5.000) = 3711.000