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^
(a <- rowSums(matrix(as.numeric(unlist(strsplit(as.character(100:999),''))),nrow=900,byrow=TRUE)^3))[a==100:999]
[1] 153 370 371 407
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 :(
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 ;)