Let’s take 13 as the value of N and try to calculate the expected value (EV13).
EV13=13×131%1+2%1+...+13%1+13×131%2+2%2+...+13%2......+13×131%13+2%13+...+13%13 numerator={1%1+2%1+...+13%1}+...+{1%13+2%13+...+13%13} ={0+0+...+0}+{1+0+1+0+...+1}+{1+2+0+1+2+0+1+...+1}+...+{1+2+...+12+0} ={⌊113⌋×(0)}+{⌊213⌋×(1)+1}+{⌊313⌋×(1+2)+1}+{⌊413⌋×(1+2+3)+1}+{⌊513⌋×(1+2+3+4)+1+2+3}... ={⌊113⌋×i=0∑0i}+{⌊213⌋×i=0∑1i+i=0∑13%2i}+{⌊313⌋×i=0∑2i+i=0∑13%3i}+{⌊413⌋×i=0∑3i+i=0∑13%4i}+{⌊513⌋×i=0∑4i+i=0∑13%5i}... =j=1∑13{⌊j13⌋×i=0∑j−1i+i=0∑13%ji} EVN=N2∑j=1N( ⌊jN⌋×∑i=0j−1i) +N2∑j=1N( ∑i=0N%ji) Therefore, for any given M, we have to calculate:
N=1∑M(N2∑j=1N( ⌊jN⌋×∑i=0j−1i) +N2∑j=1N( ∑i=0N%ji) ) There are almost M×M number of terms each of which we can calculate in constant time. So the complexity would be O(M×M).
But we can optimize further. To do that, we have find the sub sequences of this series that contain same numerators or denominators. Then we can calculate each of those sub-sequences in constant time.
Let's optimize the first part first.
N=1∑MN2∑j=1N( ⌊jN⌋×∑i=0j−1i) =x=1∑MN=1∑MN2⌊xN⌋×∑i=0x−1i =x=1∑M( i=0∑x−1i×N=1∑MN2⌊xN⌋) Now, let's focus on ∑N=1MN2⌊xN⌋.
=( 120+...+(x−1) 20) +( x21+...+(2×x−1) 21) +...+( (⌊xM⌋×x−x)2⌊xM⌋−1+...+(⌊xM⌋×x−1) 2⌊xM⌋−1) +( (⌊xM⌋×x)2⌊xM⌋+...+M2⌊xM⌋) We can calculate this sum in M/x complexity if we precalculate cumulative sum of i21 from 1 to M.
So for x=1 to M, total complexity will be near M log(M).
Now, for the second part:
N=1∑MN2∑j=1N( ∑i=0N%ji) =N=1∑MN2∑j=1N( 2( N%j) ( N%j+1) ) =N=1∑M2×N2∑j=1N( N%j) ( N%j+1) =x=1∑MN=1∑M2×N2( N%x) ( N%x+1) Now, let's focus on ∑N=1M2×N2( N%x) ( N%x+1) .
Let N=k×x+j. Therefore N%x=j.
=k∑j∑2×(kx+j)2j(j+1) =k∑j∑21×{1+kx+j1−2kx+(kx+j)2(kx)2−kx} The summation is modified in a way so that there are no variable j remains in the numerator. Now we can calculate the inner sum in constant time. So, once again, the total complexity reduced to M log(M).