7-38 數列求和-加強版 (20 分)
這個題和之前的一個階乘問題比較相似,因爲要防止數據溢出,所以都要要用數組來保存數字的位數。
在這個問題中同樣用這樣的方法。
1、用count來記錄位數,用index來指示進位。
2、這個問題中有一個地方我沒有優化好,就是第一個元素的輸出有的時候還是0。所以最後用了flag標誌,來消除錯誤的輸出。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,n;
int count = 0;
int index = 0;
int b[1000000] = {0};
int temp;
int flag = 1;
scanf("%d %d",&a,&n);
for(int i=0;i<n;i++)
{
temp = a*(n-i);
index = count;
while(temp){
b[index] += temp%10;
temp /= 10;
if(b[index] >= 10)
{
b[index] -= 10;
b[index+1] += 1;
}
index++;
}
count++;
}
for(int j=count;j>=0;j--)
{
if(flag && b[count] == 0){
flag = 0;
continue;
}
printf("%d",b[j]);
}
if(n == 0) printf("0\n");
return 0;
}