Mustafa ef - 9 months ago 62

R Question

`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)]

How can I print Armstrong numbers between 1 to 1000000? I wrote this code, but it only prints

`1 153 370 371 407`

Answer Source

Here is my solution to this problem:

```
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
```