杨辉三角形算法

【项目 2-杨辉三角】编写程序,打印出以下形式的扬辉三角形。杨辉三角是一个由数字排列成的三角形数表,一般形式如下:

             1
         1 1
        1 2 1
       1 3 3 1
      1 4 6 4 1
     1 5 10 10 5 1

    ......................................................

杨辉三角最本质的特征是,它的两条斜边都是由数字1组成的,而其余的数则是等于它肩上的两个数之和。   一、使用一维数组:据“F(x)=F(x)+F(x-1)”计算。此算法比较快,但数据受数组大小限制。可以将杨辉三角形的值放在一个方形矩阵的下半三角中,如果需打印 7 行杨辉三角形,应该定义等于或大于 7X7 的方形矩阵,只是矩阵的上半部和其余部分并不使用。

杨辉三角形具有如下特点:

  • 第 0 列和对角线上的元素都为 1。
  • 除第 0 列和对角线上的元素以外,其它元素的值均为前一行上的同列元素和前一列元素之和。

代码:

// 杨辉三角形算法.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;
int factorial(int n);
int combine(int a, int b);
void space(int t, int line);

int _tmain(int argc, _TCHAR* argv[])
{
	int line;
	cout<<"Please Input the line number :";
	cin>>line;

	while(line!=-1){
		for( int i=1;i<line;i++){
			space(i,line);
			for(int j =0; j<i; j++){
				cout << combine(j, i-1)<<"  ";
			}
			cout<<endl;
		}
		cout <<endl<<" Please Input the line number: (enter -1 to quit) ";
		cin>>line;
	}
	return 0;
}

int factorial(int n){
	int i =1;
	int product =1;
	while(i<=n){
		product =product*i;
		i++;
	}
	return product;
}

int combine(int a, int b){
	int result;
	if( a==0||b==0)
		return 1;
	else
		result = factorial(b)/(factorial(a)*factorial(b-a));
	return result;
}
void space ( int t, int line){
	for(int p =1; p<=(line-t);p++)
		cout <<" ";
}

输出结果:


转载请注明出处:http://blog.csdn.net/utimes/article/details/8453961

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值