can anyone solve it without simple for loop? more efficient approach
# | User | Rating |
---|---|---|
1 | jiangly | 3640 |
2 | Benq | 3593 |
3 | tourist | 3572 |
4 | orzdevinwang | 3561 |
5 | cnnfls_csy | 3539 |
6 | ecnerwala | 3534 |
7 | Radewoosh | 3532 |
8 | gyh20 | 3447 |
9 | Rebelz | 3409 |
10 | Geothermal | 3408 |
# | User | Contrib. |
---|---|---|
1 | maomao90 | 174 |
2 | awoo | 164 |
3 | adamant | 163 |
4 | TheScrasse | 159 |
5 | nor | 158 |
6 | maroonrk | 156 |
7 | -is-this-fft- | 151 |
8 | SecondThread | 147 |
9 | orz | 146 |
10 | pajenegod | 145 |
can anyone solve it without simple for loop? more efficient approach
Name |
---|
First realize the sum is equivalent to n * m — sum(floor(n / i^2) * i^2). This is because a mod b is equal to a — floor(a / b) * b. Now, you just need to iterate over the factors x of n, figure out the range of i where floor(n / i^2) = x, and use the sum of consecutive squares to find the sum of i^2 in that range and multiply that by x. Total complexity O(sqrtn).
I swear I'll learn latex one day lol...
But won't Root N solution time out given that N is upto 1e18.
It's $$$O(N^\frac{1}{3})$$$ if you consider only distinct values of $$$\frac{N}{i^2}$$$. (by a similar argument as to why there are only $$$O(\sqrt{N})$$$ distinct values of $$$\frac{N}{i}$$$.
Hi thanks for the response. I tried analyzing for a while but could not understand why cube root N. Could you please explain or maybe just share a link to some article that explains it.
If $$$i \le 10^6$$$, you can do it violently.
If $$$i > 10^6$$$, $$$\lfloor \frac{N}{i^2} \rfloor <= 10^6$$$. So there are $$$O(N^{\frac{1}{3}})$$$ distinct values.
Amazing, Thanks a lot.
Rip I didn't consider that. Ig you'd do the same thing but need something more clever to only consider values of n / i^2, which the user above says is possible, though I'm unaware how to do that.
I came with the following Root N solution.
Simply keep adding N%(i^2) till i^2 exceeds N at some value i = j. (j is atmost ceil(root(N)))
For all remaining values from j to M, simply add (M-j+1)*N to the total. As N % ( value larger than N) = N.
But again this will time out.