Mustafa ef Mustafa ef - 1 month ago 14
R Question

Print Armstrong numbers between 1 to 1000000

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
numbers. I want to print 1 to 1 million Armstrong numbers.

J_F J_F
Answer

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