JOJ1267:Pascal's Triangle of Death

传送门:http://acm.jlu.edu.cn/joj/showproblem.php?pid=1267

一道大数加法的题,Pascal三角就是中国的杨辉三角,每个位置的求法不用我说了,说一下大数加法的思想。

C++中整数支持最高的数位是无符号的long long,也就是2^64,也就是18446744073709551616,这么小的数位完全不够10^60运算,所以要引入大数运算方法。

用数组记录一个数,比如123用数组a记录,就是a[0] = 3, a[1] = 2, a[2] = 1。

如果之间做加法比如,123 + 1234,那就循环从0开始,长度是最长的那个数组,c[0] = a[0] + b[0], c[1] = a[1] + b[1].....如果数组存的大于等于10,那就除10,余数保存,商数进位。

详细的见代码吧,用class定义大数的话,可以重载运算符,这样更方便了....

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=70;
class bignum                        //定义大数类
{ 
    int num[maxn+1];
    public:
    bignum(){memset(num,0,sizeof(bignum));}
    friend bignum operator +(bignum &a,bignum &b);
    friend ostream &operator <<(ostream & cout,const bignum &a);
    bignum & operator =(int n);
    bool operator >(int n)
    {
    for(int i=0;i<maxn+1;i++) if(num[i]) return 1;
    return 0;
    }
};
ostream &operator <<(ostream & cout,const bignum &a)     //重载了输出符号
{
    for(int i=0,flag=0;i<maxn+1;i++)
    {
        if(i==maxn||flag||a.num[i])
        {
            cout<<a.num[i];flag=1;
        }
    }
    return cout;
}
bignum & bignum::operator =(int n)                      //赋值符号,将一个int类型的数转化成大数类型
{
    memset(num,0,sizeof(num));
    int i=maxn;
    while(n)
    {
        num[i--]=n%10;
        n/=10;
    }
}
bignum operator +(bignum &a,bignum &b)                  //大数加法的实现
{
    bignum temp;
    int t=0;
    for(int i=maxn;i>=0;i--)
    {
        temp.num[i]=a.num[i]+b.num[i]+t;
        t=temp.num[i]/10;
        temp.num[i]%=10;
    }
    return temp;
}
int main()
{
    printf("1\n1 1\n");
    bignum t,l,a[210];
    a[0]=1;a[1]=1;
    for(int ci=2,i;ci<205;ci++)
    {
        cout<<1;
        l=0;
        for(i=1;i<ci;i++)
        {
            t=a[i-1]+a[i];
            cout<<" "<<t;
            if(l>0) a[i-1]=l;
            l=t;
        }
        a[i-1]=l;
        a[ci]=1;
        printf(" 1\n");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值