Wednesday, September 28, 2011

Project Euler - Problem Four

OH GOD THEY JUST NEVER STOP.

So I'm on problem four.  This one is fairly simple, and is honestly a bunch easier for me than the prime numbers one was. Maybe that's just because I had an entire chemistry lecture to think about this one. Either way though, it's a fairly straightforward one.

In fact....I think I'll actually include a little lesson with this one. First, let's state the problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

The first real question is how we're going to check for whether a number is a palindrome or not. Everything else just falls into place after that.
Here's how to do it!

Modulus.

Whaaaa?

Really though. Modulus is just a division's remainder. So, mod ten should remove the last digit of a number. Check it out with some sort of math machine. 987654321 % 10 yields a result of 1. This means that you're able to get the last digit of the number if you mod ten. (HINT HINT)
So if you do n%10 to get the last digit, what do you do next?
Well...you get the idea. You do this:

rev = rev * 10 + dig;               // This will add the result to a number. (HINT: This is
                                                                 // going to be the opposite of the number you put in.
        num = num / 10;         //  This part will remove the number you just put into rev
                                                           

Now, you can apply this fairly easily into a function. I personally did mine as a Boolean function. I'll post a screenshot of my code below.

This one is the function:
This one is going to be the main loops that do the multiplication:
This one is the whole program:


Anyway, that's the solution to the fourth Project Euler problem. More to come? Maybe.



No comments:

Post a Comment