R Examples

R Program - Calculate sum of Squares of Natural numbers



In Mathematics, the natural numbers are all positive numbers which is used for counting like 1, 2, 3, 4, and so on. The smallest natural number is 1.

Objective: Write a R program which returns sum of squares of natural numbers starting from 1 to given natural number n, (12 + 22 + 32 + ... + n2).

Method 1: Using while loop

The example below shows how to use while loop to calculate sum of squares of first n natural numbers.

n <- 10
i <- 1
sum <- 0

#calculating sum of squares from 1 to n
while(i <= n) {
  sum <- sum + i*i
  i <- i + 1  
}

sprintf("Sum is: %d", sum)

The above code will give the following output:

[1] "Sum is: 385"

Method 2: Using for loop

The same can be achieved using for loop. Consider the example below:

n <- 10
sum <- 0

#calculating sum of squares from 1 to n
for (i in c(1:n)) {
  sum <- sum + i*i
}

sprintf("Sum is: %d", sum)

The above code will give the following output:

[1] "Sum is: 385"

Method 3: Using Recursion

Similarly, recursion can be used to calculate the sum.

#recursive function
Sum <- function(n) {
  if(n == 1) {
    return (1)
  } else {
    return (n*n + Sum(n-1))  
  }
}

sprintf("Sum of Squares of first 10 natural numbers: %d", Sum(10))
sprintf("Sum of Squares of first 20 natural numbers: %d", Sum(20))

The above code will give the following output:

[1] "Sum of Squares of first 10 natural numbers: 385"
[1] "Sum of Squares of first 20 natural numbers: 2870"

Method 4: Using Mathematical Formula

The sum of squares of first n natural numbers can be mathematically expressed as:

Sum of Squares of Natural numbers
n <- 10

#calculating sum of squares from 1 to n
sum <- n*(n+1)*(2*n+1)/6

sprintf("Sum is: %d", sum)

The above code will give the following output:

[1] "Sum is: 385"