Solving one problem I encountered one problem. I needed calculate one interesting sum: sigma(N / i), where (1 <= i && <= K). How we can do it as fast as possible. We can do it using complexity sqrt(N) moving from two ends. Following code demonstate this approach.
long smart(long N, long K) { long res = 0; long t = (long)Math.sqrt(N * 1.0); for (long i = 1; i * i < N; ++i) { if (i <= K) res += N / i; long lo = Math.max(N / (i + 1), t); long hi = Math.min(N / i, K); if (hi > lo) res += (hi - lo) * i; } if (t * t == N && t <= K) res += t; return res; }After it I recall one neerc problem. But there we need compute a little different sum: sigma(N % i), where (1 <= i && <= K). So we can replace N % i to (N - N / i * i) and addopt previous code to calculate sigma(N / i * i).
No comments:
Post a Comment