Program for Armstrong number in r

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

提交回复
热议问题