Thursday, April 26, 2012

Project Euler


I've always had a fondness for math.  I've always been pretty good at solving math problems too.  Today, a friend at work made me aware of Project Euler.  For those of you who don't know (probably most of you), Project Euler is "a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve".  Man, solving math problems with programming?  Where do I sign up?

So, I've begun my struggle to get through the 381 problems listed on the site.  Problems 1 and 2 were easy, things that we had to do in college.  Problem 3 is a little tougher, but still pretty easy.  That's how far I've gotten in an hour.  I'm going to keep going though, I'll update the blog with my progress occassionally.

Spoiler alert: I'm posting answers to problems 1 and 2 below.  Don't read if you're going to attempt this.  I'm using Java as my language of choice to solve these problems.

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 first solved this recursively, but was getting stack overflow errors, so I went to the simpler method of brute force.

private static int MAX = 1000;
private static int calculate() {
int sum = 0;
for(int index = 0; index < MAXindex++)
if(index % 3 == 0 || index % 5 == 0)
sum += index;
return sum;
} //end of calculate method

Problem 2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...  By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

private static int MAX = 4000000;
private static int calculate() {
int sum = 0;
int first = 1;
int second = 2;
while(second <= MAX) {
int temp = first + second;
if(second % 2 == 0)
sum += second;
first = second;
second = temp;
} //end of while loop
return sum;
} //end of calculate method

There you have it.  Notice that I haven't posted the results of running these.  Gotta leave something to you guys!

No comments:

Post a Comment