码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-24 17:26:45      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:algorithm

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(" ");
        }
    }
}


技术分享








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

技术分享



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

标签:algorithm

原文地址:http://blog.csdn.net/cinmyheart/article/details/43086233

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!