1. 程式人生 > >UVALive - 3521 Joseph's Problem (整除分塊)

UVALive - 3521 Joseph's Problem (整除分塊)

printf print 給定 clas com 發現 ble col include

給定$n,k$$(1\leqslant n,k\leqslant 10^9)$,計算$\sum\limits _{i=1}^nk\: mod\:i$

通過觀察易發現$k\%i=k-\left \lfloor \frac{k}{i} \right \rfloor*i$,因此我們考慮把$\left \lfloor \frac{k}{i} \right \rfloor$的值相同的$i$分成一組直接求和,復雜度為$O(\sqrt{n})$。

整除分塊原理(選自某dalao博客)

 1 #include<bits/stdc++.h>
 2 
 3 using namespace std;
4 typedef long long ll; 5 ll n,k; 6 7 int main() { 8 while(scanf("%lld%lld",&n,&k)==2) { 9 ll ans=0; 10 for(ll l=1,r; l<=n; l=r+1) { 11 r=k/l&&k/(k/l)<n?k/(k/l):n; 12 ans+=k*(r-l+1)-(k/l)*((l+r)*(r-l+1)/2); 13 } 14 printf("
%lld\n",ans); 15 } 16 return 0; 17 }

UVALive - 3521 Joseph's Problem (整除分塊)