打印阿姆斯壮的数字在1到1000000之间

时间:2016-10-28 12:01:43

标签: r

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

s <- 1:1000000
s[armstrong(s)]

如何在1到1000000之间打印阿姆斯壮数字?我写了这段代码,但它只打印1 153 370 371 407个数字。我想打印1到100万阿姆斯特朗号码。

2 个答案:

答案 0 :(得分:1)

以下是我对此问题的解决方案:

s <- 99:1000000

armstrong <- vapply(s, function(x) {

    tmp <- strsplit(as.character(x), split="")

    exponent <- length(tmp[[1]])

    sum <- sapply(tmp, function(y)sum(as.numeric(y)^exponent))

return(sum == x)
},FUN.VALUE = 1)

s[armstrong == 1]

# [1]    153    370    371    407   1634   8208   9474  54748  92727  93084
#[11] 548834

答案 1 :(得分:0)

试试这个:

s <- 1:1000000
s[sapply(s, function(x) 
 sum(as.integer(unlist(strsplit(as.character(x), split="")))^nchar(as.character(x))) == x)]
 #[1]      1      2      3      4      5      6      7      8      9    153    370    371    407   1634   8208   9474  54748  92727  93084 548834
相关问题