Problem E
Simple Addition
Input: Standard Input
Output: Standard Output
Let’s define a simple recursivefunction F (n), where
Let’s define another function S (p,q),
In this problem you have toCalculate S (p, q) on given valueof pand q.
Input
The input filecontains several lines of inputs. Each line contains two non negative integers p and q (p <= q) separatedby a single space. pand q will fit in 32 bit signedinteger. In put is terminated by a line which contains two negative integers.This line should not be processed.
For each set ofinput print a single line of the value of S(p, q).
SampleInput Output for Sample Input
1 10 10 20 30 40 -1 -1 | 46 48 52 |
其实这个有点像算一个数阶乘末尾有多少个零的思路。那个是算有多少5,不断的除以5,这个也差不多。
先看1到10, 1 2 3 4 5 6 7 8 9 1
11到20, 1 2 3 4 5 6 7 8 9 2
.. ..
.. ..
81到90, 1 2 3 4 5 6 7 8 9 9
发现10位数也产生了1到9。
从101 到 199和从1到99一样,但f(100)=1..以此类推..f(200)=2..
也就是个位数在产生1-9,十位数产生他自己的1-9,百位数产生他自己的1-9....在往后也一样。
所以如果算0到N的和,先把N除以10,这时是算的个位数不是0的,除数就是产生了几组1-9,余数n就是余下的1到n,求和就行了。接着N再除以10,这时是算的个位数是0十位数不是0那些产生的,再这样算百位数不是0的。。。最后加起来就是0到N的。
f(Q)-f(P-1)就是答案。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
long long f(long long n){
long long x,ret=0;
while(n){
x=n%10;
n/=10;
ret+=n*45+(x*(x+1)/2);
}
return ret;
}
int main(){
// freopen("in.txt","r",stdin);
long long P,Q;
while(scanf("%lld%lld",&P,&Q),P>=0||Q>=0){
printf("%lld\n",f(Q)-f(P-1));
}
return 0;
}