# 求s=a+aa+aaa+aaaa+aa...a的值问题的C语言延伸代码图解(大数据也OK)

2017-12-26 10:25:09来源:http://www.dotcpp.com/blog/3970.html作者:极客头条人点击

1.n个数相加，考虑到进位如99999+9999，需要长度为n+1的数组存放结果；

2.如图，个位结果为n- 0 个a的和，十位结果为n- 1 个a的和...万位为n- 4 个a的和；

for ( int i = n; i > 0; i-- )
sum[i] += i * a;

3.求出每位的和后，处理进位：从个位数开始，每一位先向前面一位进位，然后再求这一位对应数值（图中先蓝色，后绿色）

for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}

4.输出结果：如果sum[0]==0的话，最高位没有收到进位，输出sum[1]到sum[n],否则输出sum[0]到sum[n];

if ( sum[0] == 0 )
{
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );

#include <stdio.h>
#include <malloc.h>
void format( int *sum, int n );
void function( int *sum, int a, int n );
/*===================================================*/
int main()
{
inta, n;
int*sum;
scanf( "%d%d", &a, &n );
sum = (int *) malloc( (n + 1) * sizeof(int) );
format( sum, n );
function( sum, a, n );
return(0);
}
/*===================================================*/
void format( int *sum, int n )
{
for ( int i = 0; i <= n; i++ )
sum[i] = 0;
}
/*===================================================*/
void function( int *sum, int a, int n )
{
for ( int i = n; i > 0; i-- )
sum[i] += i * a;
/*------------------------------------*/
for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}
/*------------------------------------*/
if ( sum[0] == 0 )
{
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );
return ;
}

#include <stdio.h>
#include <malloc.h>
#include <math.h>
void format( int *sum, int n );
void function( int *sum, int a, int n );
/*===================================================*/
int main()
{
inta, n;
int*sum;
scanf( "%d%d", &a, &n );
sum = (int *) malloc( (n + 1) * sizeof(int) );
format( sum, n );
function( sum, a, n );
return(0);
}
/*===================================================*/
void format( int *sum, int n )
{
for ( int i = 0; i <= n; i++ )
sum[i] = 0;
}
/*---------------------------------------------------*/
void function( int *sum, int a, int n )
{
for ( int i = n; i > 0; i-- )
sum[i] += i * fabs( a );
/*------------------------------------*/
for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}
/*------------------------------------*/
if ( sum[0] == 0 )
{
if ( a < 0 )
printf( "-" );
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else{
if ( a < 0 )
printf( "-" );
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );
}
return;
}