4
\$\begingroup\$

I am attempting to learn R programming by going through the questions in Project Euler.

The code below is my solution to problem 5 which asks for the smallest number that is evenly divisible by 1 through 20.

The code works but takes a very very long time. Project Euler states that all of their problems should take a modern computer < 1 minute.

I know R is not as efficient as other languages but would it be possible to make my solution more efficient?

divis <- function(){
  count = 11
  tst <- 1:20 %% count # create vector of remainders
  while(sum(tst) != 0){ # test if all remainders are 0
    count <- count + 1
    tst <- count %% 1:20
    print(count)
    print(tst)
    }
  }
}
\$\endgroup\$
4
\$\begingroup\$

You should change the algorithm in order to make your program run faster. The while loop is performed over 200 million times (printing out information in every iteration) until it reaches the desired number.

If you calculate the answer using LCM (taking the least common multiple of all numbers between 1 and 20), the program should run instantly in pretty much any programming language.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.