mgroves

Project Euler 5, 6, and 7

#5 - What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

I did a slow, brute force algorithm, and a fast algorithm using Euclid's algorithm to get GCD/LCM. The slow method is to simply start guessing, incrementally, and seeing if the guess modulus of 1-20 is 0. The second method requires you to know that the least common multiple (LCM) of x,y,z is the same thing as LCM(x,LCM(y,z)). The LCM function is transitive (or whatever, I'm not a math guy). Therefore, you just loop from 2 to 20, and get the accumulative LCM. The LCM function can be written to be dependent on the greatest common denominator (GCD) function, which can be implemented efficiently using Euclid's algorithm.

At this point, I created a "MathHelper" static class to hold methods like GCD and LCM for future use (for Project Euler or otherwise).

Euler himself

#6 - Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

I wrote two methods: SumOfTheSquaresForNumbers1Through(n) and SquareOfTheSumForNumbers1Through(n), both implemented in a very straightforward way--no surprises or anything fancy here. Works very efficiently too.

#7 - What is the 10001st prime number?

I got in a bit of a rush here for some reason, so I cranked out a very brute force solution, just to "get the answer". I felt hollow right away, and decided to take a break after this problem. I read the solution notes which outlined a more efficient way to test if a number is prime or not. I added this implementation to the MathHelper class. Anyway, this problem made me slow down and rethink why I'm doing these problems: it's not to "just solve them" in some sort of competitive sense, and it's not to learn a bunch of mathy stuff either. The point, for me, is to practice my programming, test my own skills, and maybe learn new ways to think about program/method design.

Well, that's all for now. As always, check out the latest source at codeplex, which will almost surely be farther ahead than my blog.

1 Response to Project Euler 5, 6, and 7 Article comments Feed

1

GrandTheftNintendo

Yes dude. I really dig the Number Theory.

Posted at January 30, 2010 on 1:00am

Write a response

Play nice. Be constructive. Allowed HTML tags are: <a>, <strong>, <em> and <blockquote>

« Turning an NAS drive… Bring in the noise, … »