For the following code :
s = 0 ;
for(i=m ; i<=(2*n-1) ; i+=m) {
if(i<=n+1){
s+=(i-1)/2 ;
}
else{
s+=(2*n-i+1)/2 ;
}
}
I want to change the complexity of the code from O(n)
to O(1) . So I wanted to eliminate the for loop . But as
the sum s stores values like (i-1)/2 or (2*n-i+1)/2 so eliminating the loop involves tedious calculation of floor value of each (i-1)/2 or (2*n-i+1)/2 . It became very difficult for me to do so as I might have derived the wrong formula in sums of floors . Can u please help me in Changing complexity from O(n) to O(1). Or please help me with this floor summations . Is there any other way to reduce the complexity ? If yes … then how ?
As Don Roby said, there is a plain old arithmetic solution to your problem. Let me show you how to do it for the first values of i.
* EDIT 2 : CODE FOR THE LOWER PART *
How do I come up with it? I take
I make a change
I pose
a=Math.floor(n+1/m). There are 3 cases :m is pair, then interior of the loop is
s+= p*j. The result ism is impair and the iterator j is pair
m is impair and the iterator j is impair
When m is impair, you can write
m = 2p + 1and the interior of the loop becomesp*jis the same as before, now you need to break the division by assuming j is always pair or j always impair and summing both values.The next loop you need to compute is
which is the same as
This loop is similar to the first one, so there is not much work to do…
Indeed this is tedious..