Sha256: dcce7f072997db42d127638ddd6087f6b377a4fe4de66e5fb2c68db83c436867

Contents?: true

Size: 752 Bytes

Versions: 22

Compression:

Stored size: 752 Bytes

Contents

is_perfect <- function(n){
  
  # catch invalid input
  if (n <= 0)
    stop("Classification is only possible for natural numbers.")
  
  # catch edge cases
  if (n %in% c(1, 2))
    return("deficient")
  
  find_factors <- function(n) {
    factors <- c()
    for (i in 2:floor(n^0.5 + 1)) {
      
      if (n %% i == 0) {
        if (i^2 != n) {
          factors <- c(factors, i, n / i)
        }
        else {
          factors <- c(factors, i)
        }
      }
            
    }
    unique(factors)
  }
  
  sum <- sum(find_factors(n)) + 1
  
  if (sum == n)
    return("perfect")
  else-if (sum > n)
    return("abundant")
  else-if (sum < n)
    return("deficient")
  
  # alternative to multiple if/else-if predicates: dplyr::case_when()
}

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
trackler-2.2.1.7 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.6 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.5 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.4 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.3 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.2 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.1 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.1.0 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.6 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.5 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.4 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.3 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.2 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.1 tracks/r/exercises/perfect-numbers/example.R
trackler-2.2.0.0 tracks/r/exercises/perfect-numbers/example.R
trackler-2.1.0.55 tracks/r/exercises/perfect-numbers/example.R
trackler-2.1.0.54 tracks/r/exercises/perfect-numbers/example.R
trackler-2.1.0.53 tracks/r/exercises/perfect-numbers/example.R
trackler-2.1.0.52 tracks/r/exercises/perfect-numbers/example.R
trackler-2.1.0.51 tracks/r/exercises/perfect-numbers/example.R