CPCRC1C - Sum of Digits
Majid is a 3rd-grade elementary student and quite well in mathematics. Once, Majid's teacher asked him to calculate the sum of numbers 1 through n.
Majid quickly answered, and his teacher made him another challenge. He asked Majid to calculate the sum of the digits of numbers 1 through n.
Majid did finally find the solution. Now it is your turn, can you find a solution?
Input
Two space-separated integers 0 <= a <= b <= 109.
Program terminates if a and b are -1.
Output
The sum of the digits of numbers a through b.
Example
Input:
1 10
100 777
-1 -1
Output:
46
8655
#include<bits/stdc++.h>
using namespace std;
long long f(long long x)
{
long long ans=0;
while(x!=0)
{
ans+=x%10;
x/=10;
}
return ans;
}
long long dfs(long long a,long long b,long long t)
{
if(a==0)
a=1;
if(b==0)
return 0;
if(a>b)
return 0;
long long sum=0;
long long a1=((a-1)/10+1)*10;
long long b1=b/10*10;
if(a1>b1)
{
for(long long i=a;i<=b;i++)
sum+=f(i)*t;
return sum;
}
for(long long i=a;i<=b;i++)
{
if(i%10==0)
{
sum+=45*(b1-a1)/10;
i=b1;
}
else
sum+=i%10;
}
long long l=a1-a;long long r=b%10+1;
long long ans=(sum+l*f(a/10)+r*f(b/10))*t+dfs(l==0?a/10:a/10+1,r==0?b/10:b/10-1,t*10);
return ans;
}
int main()
{
long long a,b;
while(1)
{
scanf("%lld%lld",&a,&b);
if(a==-1&&b==-1)
break;
printf("%lld\n",dfs(a,b,1));
}
return 0;
}