Home > Back-end >  I need to create a function that find the sum of the first N (passed as arguments) whole numbers
I need to create a function that find the sum of the first N (passed as arguments) whole numbers

Time:11-17

Write a function Sum_whole that find the sum of the first N (passes as arguments) whole numbers. Assign the result to the variable "V" and return it

print(sum_whole(42))
print(sum_whole(13))
print(sum_whole(1))

CodePudding user response:

Here are two examples: one in base R and one using the purrr package from the tidyverse.

A base R version:

Sum_whole <- function(N) {
    Reduce(` `, seq_len(N))
}
Sum_whole(5)
#> [1] 15

A tidyverse version using purrr:

library(purrr)
Sum_whole <- function(N) {
    purrr::reduce(seq_len(N), ` `)
}
Sum_whole(5)
#> [1] 15

CodePudding user response:

Isn't the question just this one-liner?

Sum_whole <- function(N) sum(seq_len(N))

Sum_whole(5)
#[1] 15
Sum_whole(43)
#[1] 946
  •  Tags:  
  • r
  • Related