Digit Sum
Description
The security system for Associated Computer Informatics Systems (ACIS) has an interesting test to check the identity for authorized personal. These persons have got a piece of software that allowed them to calculate, given two integer positive numbers M and N, what is the sum of the decimal digits in the sequence M, M + 1, ..., N. Then, when somebody is trying to access ACIS system, he/she is asked to answer the question of the sum for some M and N that are provided at that moment, by means of the given software.
ACIS programmers have developed a rather naïve algorithm only to verify that the method calculates the right answer. Now they are interested in developing a faster algorithm, in order to stop unauthorized users (who may be detected because they do not answer the sum question fast enough). And then you have been hired to help ACIS programmers to find such a method.
Input
The problem input consists of several cases, each one defined by a line with two integer numbers, M and N, without leading blanks and separated by a blank. You may assume that 1 M N 109. The end of the input is signaled by a line with two zero values.
Output
For each case, output a line with the sum of the decimal digits for the sequence M, M + 1, ..., N.
Sample Input
3 8
5 18
1 50
0 0
Sample Output
33
80
330
刚开始写博客还有很多不熟悉,见谅
题目的意思是求出从m到n的所有的数的每一位的和
我的思路是分别求出从1到n的和、从1到m的和,相减再加上m数字的各位和
关键是求出每一位数字和,如果用循环的话,直接超时,所以找规律
我是定义一个a数组,用来存储从1到99,999,9999,99999… 的各位和,这样就可以对应相应位置上的数
#include<stdio.h> #include<string.h> long long int a[11]; void init(){ long long int i,j; for(i=0;i<=10;i++) a[i]=0; for(i=2,j=1;i<=10;i++,j*=10){ //因为从1到9的和为45,而位数增加以为,对应上一位就需要增加十倍 a[i]=45*j+10*a[i-1]; } } long long int f(long long int x){ //求从1到x的各位和 long long int i,temp=x,flag=1,num=0,ans=0,fflag=1; while(temp) { long long int k=temp%10; if(flag==1){ for(i=0;i<=k;i++) ans+=i; } else{ long long int sum=0; for(i=1;i<k;i++) sum+=i; ans = ans + a[flag]*k+ k*(num+1) + sum*fflag; } temp = temp/10; num = k*fflag + num; fflag = fflag* 10; flag++; } return ans; } long long int solve(long long int x){ //求数字x的各位和 long long int temp=x,s=0; while(temp){ s+=temp%10; temp/=10; } return s; } int main(){ long long int a,b; init(); while(scanf("%lld%lld",&a,&b)!=EOF){ if(!a && !b) break; printf("%lld\n",f(b)-f(a)+solve(a)); } return 0; }
所有评论(0)