I saw this problem on social media and looked into some fast implementations. Does anyone have some input in what could even be faster?
Euler Project Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
I used 1:1e8
as a base range to get to significant differences between the methods.
# library call only needed for the furrr:future_map_dbl solution
library(furrr)
plan(multisession)
nums <- 1:1e8
t1 <- Sys.time()
sum(nums[which(nums %% 3 == 0 | nums %% 5 == 0)])
t2 <- Sys.time()
sum(sapply(nums, function(x) if (x %% 3 == 0 | x %% 5 == 0) x else 0))
t3 <- Sys.time()
sum(purrr::map_dbl(nums, ~ if (.x %% 3 == 0 | .x %% 5 == 0) .x else 0))
t4 <- Sys.time()
sum(furrr::future_map_dbl(nums, ~ if (.x %% 3 == 0 | .x %% 5 == 0) .x else 0))
t5 <- Sys.time()
times <- c(t1, t2, t3, t4, t5)
t <- times[2:5] - times[1:4]
names(t) <- c("base-r","sapply","map_dbl","future_map_dbl")
t
The times on my computer were
Time differences in secs
base-r sapply map_dbl future_map_dbl
2.745852 186.671004 80.694654 31.161530
Using the non-base R methods add some overhead which is noticable in smaller ranges, e.g. nums <- 1:1e6
Time differences in secs
base-r sapply map_dbl future_map_dbl
0.05106783 0.78388309 1.50676894 0.32907510