Skip to content

Instantly share code, notes, and snippets.

@simonohanlon101
Last active December 3, 2018 06:01
Show Gist options
  • Save simonohanlon101/4685527 to your computer and use it in GitHub Desktop.
Save simonohanlon101/4685527 to your computer and use it in GitHub Desktop.
Project Euler - problem 1
# Project Euler // Problem 1:
# Find the sum of all the multiples of 3 or 5 below 1000
x <- 1:999
sum( x[ x %% 5 == 0 | x %% 3 == 0 ] )
# Another solution (this is really bad R practice!) could be:
x <- 1:999
j <- 0
for( i in x ){
if( x[i]%%3==0 || x[i]%%5==0 ){
y <- x[i]
j = j + y
}
}
# With 100 numbers this second solution is approximately 7 times slower than the first
# With 1000 numbers this rises to about 18
# And with 1e5 numbers? 30 times. The larger the set, the greater the difference in inefficiency
# Who cares with a runtime of <0.1s?
# Well, what if it's a billion? What if there are more complex operations involved than modulo division and addition?
# Lesson: take advantage of R's vectorisation for speed.
@hcm444
Copy link

hcm444 commented Dec 3, 2018

Damn dude R is faster then C++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment