Program for Armstrong number in r

后端 未结 3 1563
佛祖请我去吃肉
佛祖请我去吃肉 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 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 :(

提交回复
热议问题