How to get sum of multiples of 5

Viewed 84

Create a function that only shows the sum of whole numbers that are also multiples of 5 that are between the range 1,n.

So far, I got to the point where the function shows me the values that meet the above mentioned criteria, but all I gut are the Boolean values. Not sure of to change them to values so I can get the sum.

This is what I have:

sumnumbers <- function(n) {
  multiples.5 <- c(1:n)
  return(multiples.5 %% 5== 0)
}  
  
sumnumbers (n = 15)

And this is what I get:

[1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE

On the other hand, if I change the code and add the sum to the function, I only get the number of instances where the criteria is met. Example:

sumanumbers <- function(n) {
  multiples.5 <- c(1:n)
  return(sum(multiples.5 %% 5== 0))
}  
  
sumatoria (n = 15)

I get 3 when n = 15.

2 Answers

You can try

sumnumbers <- function(n) sum(seq(0, n, 5))

or

sumanumbers <- function(n) sum(which(seq(n) %% 5 == 0))
sumnumbers <- function(n) {
  multiples.5 <- c(1:n)
  return(sum(multiples.5[multiples.5 %% 5== 0]))
}  

sumnumbers (n = 15)

multiples.5 %% 5== 0 will give you a logical vector of True False. You can use it to identify the locations of the multiples of 5 in c(1,n). Thus, multiples.5[multiples.5 %% 5== 0] will extract only the numbers that are multiples of 5 so you can sum them up.

Related