Generate splitter list of a given number n

Asked

Viewed 131 times

-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 splitters of n, but when I test, with some value of n, it tells me logically if such number in the division gives 0 rest or does not give, I wonder how do I know which numbers and how do I store such numbers in a vector.

Ex: guru (3)
TRUE FALSE TRUE 

1 answer

2

To solve this problem just use which(vetor lógico).
Note that I have made two other modifications. I have included the newline to finish the cat and now the function is not limited to printing anything, 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 think 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.