Question: This is a rather simple question but somehow my code either takes long time or consumes more resource. It is a question asked in www.codewars.com which I use for R Programming practice.

Below are the two versions of the problem I coded:

Version 1 :
===========

```
f <- function(n, m){
# Your code here
if(n<=0) return(0) else return((n%%m)+f((n-1),m))
}

```

Version 2:
==========

```
#Function created to calculate the sum of the first half of the vector 
created

calculate_sum <- function(x,y){
sum = 0
for(i in x){
  sum = sum + i%%y
}
return(sum)      
}

#Main function to be called with a test call

f <- function(n, m){
# Your code here
#Trying to create two vectors from the number to calculate the sum 
#separately for each half

if(n%%2==0){

first_half = 1:(n/2)
second_half = ((n/2)+1):n

} else {

first_half = 1:floor(n/2)
second_half = (ceiling(n/2)):n
}

sum_first_half = calculate_sum(first_half,m)
sum_second_half = 0

for(j in second_half){
sum_second_half = sum_second_half+(j%%m)
}

return(sum_first_half+sum_second_half)

}

```

I am trying to figure out a way to optimize the code. For the first version it gives the following error message:

> 
> Error: C stack usage 7971184 is too close to the limit
>  Execution halted 
> 
> 
> 

For the second version it says my code took more than 7000 ms and hence was killed.

Can someone give me a few pointers on how to optimize the code in R??

Answer: 
The optimisation is mathematical, not programmatical (though as others have mentioned, loops are *slow* in R.)

Firstly, note that `sum(0:(m-1)) = m*(m-1)/2`.

You are being asked to calculate this `n%/%m` times, and add a remainder of `(n - n%/%m)(n - n%/%m + 1)/2`. So you might try

```
f <- function(n,m){
  k <- n%/%m
  r <- n - k*m
  return(k*m*(m-1)/2 + r*(r+1)/2)
}

```

which is a much less complex calculation, and will not take very long regardless of how large n or m is.

There is a risk that, if `n` is greater than 2^53 and `m` does not have enough powers of 2 in its factorisation, there will not be enough precision to calculate `k` and `r` accurately enough.
EDIT: Just Realized it is actually a trick question
I would do 

```
 n%/%m *sum(1:(m-1)) + sum( 0:(n%%m))

```

Loop are real slow in R. Also, from my experience recursive function in R doesnt help much with the speed and it takes lots of memory