Bhail
Bhail

Reputation: 407

Summation of a sequence

If n(1) = 1 ,n(2) = 5, n(3) = 13, n(4) = 25, ... I am using a for loop for summation of these terms 1 + (1*4 - 4) + (2*4 - 4) + (3*4 - 4) + ..

This is the function I am using with a for loop:

shapeArea <- function(n) {

     terms <- as.numeric(1)
     for(i in 1:n){
       terms <- append(terms, (i*4 - 4)) 
     }
    sum(terms)
}

This works fine (as shown here):

> shapeArea(3)
[1] 13
> shapeArea(2)
[1] 5
> shapeArea(4)
[1] 25

Yet I was also thinking how can I do this without saving the terms of the series in numeric vector terms. In other words is there a way to find summations of terms without saving them in a vector first. Or is this the efficient way to do this.

Thanks

Upvotes: 0

Views: 82

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388972

You can change your shapeArea function to a one-liner

shapeArea <- function(num) {
    1 + sum(seq(num) * 4) - (4 * num)
}  

shapeArea(1)
#[1] 1
shapeArea(2)
#[1] 5
shapeArea(3)
#[1] 13
shapeArea(4)
#[1] 25

Upvotes: 3

Related Questions