-2

I need a function that gives me the sum of the divisors of a number considering that number and 1 as divisors of that number.

I don't see any wrong in the code

In theory for this concrete example the answer must be 42 for 20 but I get something else.

enter image description here

  • Welcome to StackOverflow. In order to ask a better question please read [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) and [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Rui Barradas Dec 29 '18 at 16:37
  • 1
    are a *really bad* way of posting code or data. Please edit the question with the code, formated with 4 spaces before each code line. – Rui Barradas Dec 29 '18 at 16:38
  • Also, see [this](https://math.stackexchange.com/questions/22721/is-there-a-formula-to-calculate-the-sum-of-all-proper-divisors-of-a-number#22723) math.stackexchange question. – Rui Barradas Dec 29 '18 at 16:55
  • post your code as text – taygetos Dec 29 '18 at 19:03

1 Answers1

1

This code should be faster; it also evaluates the divisors and outputs the sum of the divisors in one single function:

sum_divisors <- function(dividend){
   # create a vector from 1 until half of the dividend
   x <- 1:floor(dividend/2)
   # capture the divisors
   divisors_vector <- x[dividend%%x == 0]
   # sum the divisors we found, and the dividend itself
   divisors_sum <- sum(divisors_vector) + dividend
   return(divisors_sum)
}
Ric S
  • 9,073
  • 3
  • 25
  • 51