Problem Author: | Hasan Saleh (MathModel) |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
First of all , swap the order of summation and fix the base first , base contributes nothing so
Now instead of counting zeros number by number , let's count them position by position. Fix a position p \ge 0 with place value w=y^p. A zero there must not be a leading zero , so some higher digit of is non-zero , i.e. \left\lfloor \frac{x}{wy} \right\rfloor \ge 1 , thus every such is of the form
For a fixed these are exactly the consecutive integers [h\cdot wy , h\cdot wy+w-1] , let H=\left\lfloor \frac{n}{wy} \right\rfloor :
1 \le h < H : the whole block fits below , so numbers each.
h=H : the block is cut by , so \min(w,(n \bmod wy)+1) numbers.
h > H : nothing.
So position contributes
and it exists only while wy \le n.
Notice for y > \sqrt{n} only p=0 exists , so the inner loop runs once , and for y \le \sqrt{n} it runs \log_y n times , thus the total work is .
Complexity .
#include<bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
ll n;cin>>n;
ll ans=0;
for(ll y=2;y<=n;y++){
for(ll w=1;w*y<=n;w*=y){
ll H=n/(w*y);
ans+=(H-1)*w+min(w,n%(w*y)+1);
}
}
cout<<ans<<"\n";
}
int main(){
int t;cin>>t;
while(t--){
solve();
}
return 0;
}