C++ 高精度求n的累加和

用高精度方法,求s=1+2+3+.....+n的精度值(n以一般整数输入,n<=10^100)

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main()
{
    char str1[256],str2[256];
    int a[256],b[256],c[256];
    int lena,lenb,lenc;
    int x;
    int i,j;

    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));

    cin>>str1;//输入乘数str1
    //cin>>str2;//输入乘数str2
    strcpy(str2,str1);
    lena=strlen(str1);
    lenb=strlen(str2);
    for(i=0;i<=lena-1;i++)//乘数str1存入数组a
        a[lena-i]=str1[i]-'0';

    for(i=0;i<=lenb-1;i++)//乘数str2存入数组b
        b[lenb-i]=str2[i]-'0';

    b[1]++;
    for(int i = 1; i < lenb; i++)
    {
        if(b[i]>=10)
        {
            b[i] = 0;
            b[i+1]++;
        }
        else
        {
            break;
        }
    }

    for(i=1;i<=lenb;i++)
    {
        x=0;//用于存放进位
        for(j=1;j<=lena;j++)//对乘数每一位进行处理
        {
            c[i+j-1]=a[j]*b[i]+x+c[i+j-1];//当前乘积+上次乘积进位+原数
            x=c[i+j-1]/10;
            c[i+j-1]%=10;
        }
        c[i+lena]=x;//进位
    }
    lenc=lena+lenb;


    for(i=lenc;i>=1;i--)
    {
        if(c[i]%2==0)
        {
            c[i]/=2;
        }
        else
        {
            c[i-1]+=10;
            c[i]/=2;
        }
    }

    while((c[lenc]==0)&&(lenc>1))//删除前导0
        lenc--;
    for(i=lenc;i>=1;i--)//倒序输出
    {
        cout<<c[i];
    }
    cout<<endl;
    return 0;
}

原文:https://www.cnblogs.com/--lr/p/12837290.html

posted @ 2022-06-20 17:12  萧海~  阅读(436)  评论(0编辑  收藏  举报