Author: Pete

Project Euler

Project Euler Problem 4

TACOCAT is a palindrome!Continuing on from my previous adventures in Euler, we now come to problem 4. Problem 4 asks you to find the largest palindrome that is the product of two 3 digit numbers.

My solution is brute force, and originally, I started two loops both at 999 and counted down, figuring the first palindrome found would be the largest. I was wrong, however, and was required (sticking to brute force) to check all products for palindromes and just keep the largest. The “count backwards” code returned “Using 995 and 583, the max palindrome is 580085”, which is incorrect. My correct code is as follows:

using System;

namespace ProjectEuler
{
	/// <summary>
	/// A palindromic number reads the same both ways. The largest
	/// palindrome made from the product of two 2-digit numbers is 
	///  9009 = 91 x 99.
	/// Find the largest palindrome made from the product of two 3-digit numbers.
	///  http://projecteuler.net/index.php?section=problems&id=43
	///
	/// The answer is 906609
	/// </summary>
	public class Problem4
	{
		public static void Main(string[] args)
		{
			var max = 0;
			var theI = 0;
			var theK = 0;
			
			for (var i = 100; i <= 999; i++)
			{
				for (var k=100; k <= 999; k++)
				{
					var product = i * k;
					if (IsPalindrome(product) && product > max)
					{
						theI = i;
						theK = k;
						max = product;
					}
				}
			}

			Console.WriteLine("Using {0} and {1}, the max palindrome is {2}", theI, theK, max);
		}

		public static bool IsPalindrome(int number)
		{
			var forward = number.ToString();
			var reverse = forward.ToCharArray();
			Array.Reverse(reverse);

			return forward == new string(reverse);
		}
	}
}

That returns “Using 913 and 993, the max palindrome is 906609”.

After you put in the correct answer on the Project Euler site, you are allowed to then view the forums to discuss your answers. I found some interesting math inside that made other algorithms much more efficient. Here is what I gleaned:

A six digit palindrome would be in the format abccba. If we take our real answer of 906609, that could also be written as 9(100000) + 0(10000) + 6(1000) + 6(100) + 0(10) + 9(1). The same way, our generic answer can be written as 100000a+10000b+1000c+100c+10b+1a. Simplified again, that is 100001a+10010b+1100c. You can factor 11 out of that, leaving you with 11(9091a + 910b + 100c). That means that the product would have to be easily divisible by 11 (saving you the lengthy – by comparison – palindrome check). My original algorithm ran in 9.219022 seconds on my Mac Mini running Mono. When I add in the “divide by 11 check” to short-circuit every palindrome comparison, the algorithm now runs in 1.63679 seconds. That is a HECK of an improvement. Math… I think this might just catch on!

Project Euler

Project Euler Problem Three

Optimus PrimeIt has been almost two years since I tackled Project Euler Problems One and Two. I really wanted to get back into it, so there really is no time like the present to do the work. I’m on my Mac Mini right now, so I developed this in C#.Net using MonoDevelop.

This problem needs us to find the largest prime factor of a very large number. Obviously, to do this, you need to be able to generate a set of prime numbers to work with. I have an IsPrime method that uses a very brute force method (with the shortcut of only checking as high as the square root of the number). I Googled around for ways to generate primes and looked into the Sieve of Eratosthenes, but it was a little complicated for the time I had allotted myself to work on this problem (basically the ten minutes until I had to put my son to bed). Plus, it turns out that this entire piece of code runs in under a second on my several year old Mac Mini, so there was no need to optimize yet. I know that later Project Euler problems also deal in primes, so I may need to break it out then.

Once I had that method in place, it was really a simple matter of working up to the square root of the number in the problem, 600851475143, using the same shortcut. If the number in my loop was prime and evenly divided into our number, I stored it as the current largest number. When I was done, whatever number was currently in that variable was our champion. Pretty simple logic.


using System;

namespace ProjectEuler
{
	/// <summary>
	/// The prime factors of 13195 are 5, 7, 13 and 29.
	///  What is the largest prime factor of the number 600851475143 ?
	/// http://projecteuler.net/index.php?section=problems&id=3
	///
	/// The answer is 6857
	/// </summary>
	public class Problem3
	{
		protected static double number = 600851475143;
		
		public static void Main(string[] args)
		{
			double limit = Math.Floor(Math.Sqrt(number));
			double currentLargestPrime = 0;

			for (double i = 2; i <= limit; i++)
			{
				if (IsPrime(i) && (number % i == 0))
				{
					currentLargestPrime = i;
				}
			}			
			
			Console.WriteLine(currentLargestPrime);
		}

		public static bool IsPrime(double n)
		{
			if (n%2 == 0) return false;

			var upperLimit = Math.Floor(Math.Sqrt(n));

			for (double i = 3; i <= upperLimit; i++)
			{
				if (n % i == 0) return false;
			}

			return true;
		}
	}
}

Have you attempted this problem yet? What is your solution? I’d love to see them. You can post it in the comments or post a link if you’ve blogged it already.

Windows Phone 7

Windows Phone 7 Launch Event

I’m excited about the new Windows Phone 7 device, especially developing for it. I’ve written two blogs posts about it as of this date (Filed here) and I plan on writing many more.

I also plan on buying a Windows Phone 7 when it launches and getting as many apps as I can in the marketplace.

Microsoft has long shown that it is very focused on developers and always does launch events up big. As such, the launch events that are available here:

Windows Phone 7 Launch Event - Click for Details (Edit: Link removed, since it was taken down)

are sure to be awesome.

I’ve also added a small banner in my sidebar to stay up while the events are going off for two reasons. 1) There is a contest and 2) My hope is that a lot of developers will get excited and get tons of fantastic apps in the marketplace.

Go download the tools and let’s make this platform great!

Agile

The Case for Requirements

RequirementsI was recently reading through some of my backlog of Dr. Dobb’s Journals (a PDF I receive monthly) and came across an article entitled The Requirements Payoff by Karl Wiegers. I’ve archived a copy of the PDF here and it can be found on pages 5-6.

A lot of people seem to equate “requirements gathering” with “big design up front”, which is now often vilified as being antiquated and bloated. Nothing could be further from the truth (about requirements, not BDUF). In the book Agile Principles, Patterns, and Practices in C#, Uncle Bob talks about practicing Agile in a .Net world. In every one of his examples, you have to know what your requirements are ahead of time. The process goes as follows:

  1. Gather requirements
  2. Estimate requirements to determine length of project
  3. Work requirements in iterations
  4. Gauge velocity in coding requirements against estimate
  5. Determine whether your velocity requires you to either cut requirements or extend timelines
  6. Lather, rinse, repeat

You see that the agile process doesn’t work without requirements. In the article, Wiegers says that according to a 1997 study, “Thirty percent or more of the total effort spent on most projects goes into rework, and requirement errors can consume 70% to 85% of all project rework costs”. That is a big penalty to pay for laziness or ineptitude in early requirements gathering. This doesn’t mean that the requirements collected at the beginning are rigid and inflexible. They are just a starting point. However, changing the requirements changes the estimate and also the expected cost in time and resources and can fall under the statistic quoted above.

Requirements are essential to TDD and BDD advocates, as well. The requirements are what a vast majority of the tests are written against. For instance, if the requirement is that the user name is an email address then a programmer will likely write a test (both positive and negative) verifying that the program behaves as expected when presented with an email address or a non-email address, etc. Without that requirement, a test might only be written to ensure the user name wasn’t blank and the stake-holders might be upset when the program behaves differently than they imagined in their heads (and you failed to ferret out in requirements gathering).

It is true that gathering proper requirements in advance costs time. Wiegers sums it up best, however, when he says, “These practices aren’t free, but they’re cheaper than waiting until the end of a project or iteration, and then fixing all the problems. The case for solid requirements practices is an economic one. With requirements, it’s not ‘You can pay me now, or you can pay me later.’ Instead, it’s ‘You can pay me now, or you can pay me a whole lot more later.'”

Code Tips

The Importance of jQuery ajaxSetup Cache

Johnny Cache
Just a quick note to document a “gotcha” that cost me quite a bit of time today. I am currently working on my company’s second Asp.Net MVC 2.0 application. Our first one was a huge success and (to me) MVC is way more fun and productive than WebForms, so doing as much new development using MVC instead of WebForms is a no-brainer.

Being good MVC-ites, we are doing a lot of AJAX calls. Since we are extensively using the jQuery library, we do a lot of $.ajax() and $(someSelector).load() in our code to make calls. Today, I was calling code like the following:

$('#theDivToUpdate').load('/Our/Url/Product/Edit/', {id : ourIdParameter}, function() { /* callback logic */ });

That code will call the Edit action on the ProductController and pass in the id of the product to edit. The controller gets the product details and then returns a partial to the page, which is then inserted into the div. I was trying to debug the controller action, but after I had edited a product once, the breakpoint wouldn’t catch anymore. I figured that I was dealing with a caching issue and the method wasn’t even being called, but I couldn’t find where I even had output caching configured in MVC.

I knew that I wasn’t having this problem in our previous application, so I started comparing files and looking for answers. Nothing was really giving me any clues, and everything appeared to be set up the same way. Finally, in exasperation, I did a “Find in Files” in Visual Studio in the other solution for just the word “cache” since searching for “outputcache” had failed me.

I dug through tons of results and then finally came across this little gem:

$.ajaxSetup({ cache: false });

I had seen that in the last application, had read the documentation on ajaxSetup, but I didn’t really understand all of the ramifications of it.

Apparently, jQuery in all of its awesomeness will actually cache ajax calls for you to speed up your page. That’s definitely awesome, but unexpected caching can certainly screw up your day.