Program for Armstrong number in r

后端 未结 3 1443
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 04:43

A Number is called Armstrong Number if the sum of the cube of each digit of that number is equals to the Number itself.

Example:

  • 153 = 1 + 5^

相关标签:
3条回答
  • 2021-01-20 04:51
    (a <- rowSums(matrix(as.numeric(unlist(strsplit(as.character(100:999),''))),nrow=900,byrow=TRUE)^3))[a==100:999]
    [1] 153 370 371 407
    
    0 讨论(0)
  • 2021-01-20 05:03

    A variation on a theme...

    I have in my R snippets a function from Greg Snow. I'll see if I can dig up a link later. Here's the original answer to a somewhat similar question. It's called "digits" and serves to split up a number into digits without using strsplit.

    digits <- function(x) {
      if(length(x) > 1 ) {
        lapply(x, digits)
      } else {
        n <- nchar(x)
        rev( x %/% 10^seq(0, length.out=n) %% 10 )
      }
    }
    

    Using that function, we can do something like:

    A <- 100:999
    A[sapply(digits(A), function(y) sum(y^3)) == A]
    # [1] 153 370 371 407
    

    It is, unfortunately, the slowest of the three functions here :(

    0 讨论(0)
  • 2021-01-20 05:09

    A quick and dirty solution using ?strsplit:

    armstrong <- function(x) {
      tmp <- strsplit(as.character(x), split="")  
      cubic <- sapply(tmp, function(y)sum(as.numeric(y)^3))
      return(cubic == x)
    }
    

    E.g.:

    armstrong(c(153, 142))
    # [1] TRUE FALSE
    
    # find all 3 digit numbers:
    s <- 100:999
    s[armstrong(s)]
    # [1] 153 370 371 407
    # @CarlWitthoft: wikipedia was right ;)
    
    0 讨论(0)
提交回复
热议问题