A Week Later, I Found a Fabulously Inelegant Solution

The code is as ugly as this cable management solution. Courtesy Nate Vack on Flickr.

This one took a long time to figure out. I started last Sunday and finally got an answer today. Based on how busy my life is getting now, I may have to move to solving one problem every two or even three weeks. I will experiment with the official answer soon to learn from it, but first to explain what I did on my own.

The Problem

The problem is finding the lowest common multiple of every integer between 1 and 20. That is to say, the final answer should be divisible by each number between 1 and 20 with no remainder leftover (modulus = 0).

My Process

Snapshot of my Github commit titles

I tried a few different approaches. Most of the errors I ran into were syntax errors. I’m still learning how to code in R, so some of the approaches I tried unsuccessfully might work if applied correctly.

My first idea was to create nested testing loops. First was a while loop for the integer being below the target maximum, then I had the actual testing criteria for all the test integers and incrementation. The incrementation was an area that was a mess for me with a bunch of issues by not being written correctly. After I finally fixed it, the code did validate for integers from 1 to 10, but didn’t seem to work going up to 20. That may be because the test limit was too low, so I’ll try it again for comparison.

I then tried a few other versions of the same idea that ran into various malfunctions. My final approach wound up simply creating lists of all eligible numbers and creating nested intersections of those lists to find the answer. This works because of how intersections work in set theory. However, it took 7.045696 minutes to run, making it very inefficient.

Lessons Along the Way

As I played around with possible solutions, I learned a few things:

I learned how to unload packages. This was because I tried something requiring dplyr, which masked the intersect() function. I had to unmask it and didn’t want to restart the whole thing.

I learned about the %in% function. I saw a recreation of the intersect() function using %in% to check elements during a loop.

I also discovered set operations in base R (how I answered the question) and in dplyr. I didn’t know they existed in R before this project, but I’m happy I learned they exist!

You can check out the full commit history and my solution here.