Pascal triangle 帕斯卡三角形 杨辉三角形 二项式定理

Pascal triangle







等段时间再扯pascal triangle~

先把一年多以前打印杨辉三角形的方法贴出来(简直不认直视,越来越不敢看以前自己写的东东了)


C语言实现:

/***************************************************************
 Code writer : EOF
 Code date   : 2013.05.16
 e-mail      : jasonleaster@gmail.com

 Code description :
     Here is a demo for how to print out the pascal triangle.

*****************************************************************/
#include <stdio.h>
#include <stdlib.h>

void buildup(int S, int *n);
void putout(int S, int *n);

int main()
{
    int row = 0;
    int k = 0, m = 0, x = 0, S = 0;

    printf("Please enter the row number");
    while(!scanf("%d",&S))
    {
         while(getchar() != '\n');
         printf("please enter again!\n");
    }

    int *n = (int *)malloc((S + 1)*(S/2)*sizeof(int));

    if(!n)
    {
        printf("malloc failed!\n");
        return -1;
    }

    buildup(S, n);
    putout(S, n);
    return 0;
}

void buildup(int S, int *n)
{
    int row , k , m , x , y , a , b;
    row = k = m = x = y = a = b =0;
    
    //initialization
    for(m = 0; m < (S+1)*(S/2); m++)
    {
        n[m] = 0;
    }

    for(row = 1; row <= S; row++)
    {
        m = ((row*(row-1))/2);
        n[m] = 1;
    }

    for(row = 1;row <= S; row++)
    {
        m = ((row*(row+1))/2) -1;
        n[m] = 1;
    }

    //key method
    for(k = 2; k <= S-1; k++)
    {
        for(row = (3 + k -2); row <= S; row++)
        {
            m = ((row*(row-1))/2) - 1 + k;
            x = m - row;
            y = m - row + 1;
            a = ((row*(row+1))/2) - row;
            b = ((row*(row+1))/2) - 1;

            if( m != a && m != b)
            {
                n[m] = n[x] + n[y];
            }
            else
            {
                n[m] = 1;
            }
        }
    }

}

void putout(int S, int *n)
{
    int row , blank , rank , num;
    row = blank = rank = num = 0;

    for(row = 1; row <= S; row++)
    {
        if(row == 1)
        {
            for(blank = 1; blank <= 4*(S-row); blank++)
            {
                printf(" ");
            }
        }
        else
        {
            for(blank = 1; blank <= (S-row); blank++)
            {
                printf("    ");
            }
        }

        for(rank = 1; rank <= row; rank++)
        {
            printf("%d     ", n[num]);
            num++;
            if(rank == row)
            {
                printf("\n");
            }
            printf(" ");
        }
    }
}










                             摄于二零一四年八月十四日         秋水共长天一色 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值