Generate list of divisors of a given number n

-2
guru = function (n){

  if (n>0){
    x = (n%%(1:n) == 0)

    cat(x)
  } 
}

So, I need to create a vector that contains all the divisors of n , but when I test, with some value of n , it logically tells me whether such a number in the division gives rest 0 or not , I wanted to know how do I know what numbers and how do I store such numbers in a vector.

Ex: guru (3)
TRUE FALSE TRUE 
    
asked by anonymous 19.08.2018 / 20:10

1 answer

2

To resolve this problem, just use which(vetor lógico) . Note that I made two other modifications. I include newline to end cat and now the function is not limited to starting anything, it returns a value.

guru <- function(n){
  if (n > 0){
    x <- which(n%%(1:n) == 0)
    cat(x, "\n")
    x
  }
}

guru(3)        # Número primo
guru(8)        # Número composto

However, I believe the following is better.

guru2 <- function(n) if (n > 0) which(n%%(1:n) == 0)

guru2(3)        # Número primo
guru2(8)        # Número composto
guru2(12)       # Número composto
guru2(33331)    # Número primo
    
19.08.2018 / 20:39