<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>vi-kan.net &#187; Euler</title>
	<atom:link href="http://blog.vi-kan.net/tag/euler/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.vi-kan.net</link>
	<description>{ TODO -oVegar : insert clever text here}</description>
	<lastBuildDate>Mon, 28 Nov 2011 17:05:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Project Euler, Problem 18 &amp; 67</title>
		<link>http://blog.vi-kan.net/2010/project-euler-problem-18-67/</link>
		<comments>http://blog.vi-kan.net/2010/project-euler-problem-18-67/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 21:49:50 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=294</guid>
		<description><![CDATA[I have been struggling with a couple of Euler Problems the past days. Not so much finding the solution as finding a couple of bugs in my code&#8230; By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. [...]]]></description>
			<content:encoded><![CDATA[<p>I have been struggling with a couple of Euler Problems the past days. Not so much finding the solution as finding a couple of bugs in my code&#8230;</p>
<p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<p style="text-align: center;"><strong>3</strong><br />
<strong>7</strong> 4<br />
2 <strong>4</strong> 6<br />
8 5 <strong>9</strong> 3</p>
<p>Find the maximum total from top to bottom of the given triangle.<span id="more-294"></span>The 18th problem involves finding the optimal route from top to bottom in a pyramid  of 15 rows. It is possible to solve this using a brute force algorithm, testing every possible solution. Problem no. 67 is the exact same problem, but this time with a pyramid of 100 rows. The problem text includes a little warning, stating that a brute force approach would take a couple of billion years to complete&#8230;</p>
<p>I remember back when I was a kid, I used to solve labyrinths like &#8216;help the little mouse find its cheese&#8217;, I always started with the cheese. It was always easier to find the way back to the mouse. I would guess that the same would go for this one. If we can solve the problem from the bottom instead of the top, it should be easier to choose the right path.</p>
<div style="float: right; margin: 10px; text-align: center;">6<br />
1 7<br />
9 2 3<br />
8 5 9 3</div>
<p>So, lets start at the bottom of the four-row pyramid. We have four numbers: 8 5 9 and 3. Even though 9 is the larger one, we have no idea if 9 is where we want to end up, since the numbers leading to the first number, 8, could be higher. Imagine the third row to be 9 2 and 3. The only way down to the 8 would be through the 9 in the third row, and down to the 9 we could have come through the 2 or the 3. 8 + 9 = 17 looks like a much better total then 2 + 9 = 11 or 3 + 9 = 12. Moving up one more row, to the second row, lets imagine the numbers 1 and 7. If we went for the  8 + 9 combination, we would only have one choice up to the second row, making a total of 8 + 9 + 1 = 18. If we went for the 9 + 3 combination, the 7  would be our only choice, giving a total of 19. From the 2 in the third row, we could reach either one, but would not get a higher total any way, so lets just drop that option all together.</p>
<p>Now, what seemed like a great path, starting with 8 + 9, turned out to be beaten by another option higher in the pyramid. How could we predict that? We couldn&#8217;t. So what would make going from bottom to top a better solution then from the top to bottom? Well, we managed to throw away a couple of options. We never payed either the 5 or the 3 in the bottom row any attention. From the 5, we could have gone up through 9 or 2 in the third row, but if we have come to the 9, why should we go down to the 5 when we know that the 8 would give a better total? Same goes for the 2. Why go down to 5 for a total of 7 when we can go down to 9 for a total of 11? And that is the clue to solve this problem. We need to know what would give the greater total, left or right.</p>
<p>OK. So lets start at the bottom again, this time, with some of the numbers from the given pyramid in problem 18:</p>
<p style="text-align: center;"><span style="line-height: normal; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; font-size: small;"><img class="aligncenter" title="Last two rows" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_1.jpg" alt="" width="470" height="50" /></span></p>
<p>If we start with the 63, we could either go down to 04 or 62. Obviously, knowing this is the last row, we would go for 62 and a total of 125. From 66 we can go to 62 or 98. Once again, we would take the right path for a total of 164. From 04, we would pick 98, from 68, 27 or 89, 23 and so on.</p>
<p style="text-align: center;"><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_21.jpg"><img class="alignnone size-full wp-image-309" title="Last two rows added together" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_21.jpg" alt="" width="180" height="75" /></a></p>
<p>Now we can easily know where we want to go next from the 14th row. Lets add the 13th row:</p>
<p><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_3.jpg"><img class="aligncenter size-full wp-image-310" title="Three last rows" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_3.jpg" alt="" width="180" height="110" /></a></p>
<p>Since we already know the best path from each number in the 14th row down to the 15th, we can treat the trip from the 13th row down to the 14th in the same way. From the first number, 91, we know we can choose between 63 and 66. We know that if we choose 63, we can reach a maximum of 91 + 125 by going right from 63. If we choose 66, we know that we can reach a total of 91 + 128 by going left. From the second number, 71, we can go left through 66, or right through 04. By choosing right, we can reach a maximum of 71 + 102, so clearly left would be a better choice, which gives us 71 + 164.</p>
<p><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_4.jpg"><img class="aligncenter size-full wp-image-311" title="Three last rows added together" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_4.jpg" alt="" width="180" height="110" /></a>Do you see the pattern? I think we are ready for some code! I started out with a NumberPiramid-class. It has a method for adding a row of numbers, and a method returning the calculated maximum total.</p>
<pre class="brush: objc; title: ;">
@interface NumberPiramid : NSObject {
  NSMutableArray *rows;
}

-(void)addRow:(NSString *)stringWithNumbers;
-(int)numberOfRows;
-(int)maximumTotal;

@end</pre>
<p>The method addRow:stringWithNumbers takes all numbers for one row as a string separated by spaces. The string is split into an array of Number, a class able to hold both the number itself, and the totals for the left and right side.</p>
<pre class="brush: objc; title: ;">
-(void)addRow:(NSString *)stringWithNumbers;
{
  NSArray *numbers = [stringWithNumbers componentsSeparatedByString:@&quot; &quot;];
  NSMutableArray *row = [[NSMutableArray alloc] initWithCapacity:[numbers count]];
  for (NSString *number in numbers) {
    Number *n = [[Number alloc] initWithNumber:number];
    [row addObject:n];
    [n release];
  }
  [rows addObject:row];
  [row release];
}</pre>
<p>So now, we have an array of arrays that we can use to find our total. The method maximumTotal will first traverse the arrays bottom up, adding the numbers one by one, always keeping the larger option. I have given the Number class a convenience method maxSum, that returns the larger number of leftSum and rightSum. When we have reached the top, we have our total.</p>
<pre class="brush: objc; title: ;">-(int)maximumTotal;
{
  NSArray *row = [rows lastObject];
  NSArray *prevRow;
  for (int r = [self numberOfRows] - 2; r &gt;= 0; r--) {
    prevRow = row;
    row = [rows objectAtIndex:r];
    for (int n = 0; n &lt; [row count]; n++) {
      Number *number = [row objectAtIndex:n]&gt;
      Number *left = [prevRow objectAtIndex:n];
      Number *right = [prevRow objectAtIndex:n + 1];
      number.leftSum = number.number + [left maxSum];
      number.rightSum = number.number + [right maxSum];
    }
  }
  Number *top = [row objectAtIndex:0];
  return [top maxSum];
}</pre>
<p>And thats all there is. Problem 67 is the exact same problem, but with a larger pyramid. The numbers are given in a textfile, so we need a new method that can read the textfile line by line. Actually, I found it easier to just read the whole file into a string, using NSString initWithContentsOfFile:filename. I then split this string into lines with the same method I use to split a single row.</p>
<p>As before, the code is available <a href="http://svn.vi-kan.net/euler">through svn</a>. There is a delphi implementation too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/project-euler-problem-18-67/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 17</title>
		<link>http://blog.vi-kan.net/2010/project-euler-problem-17/</link>
		<comments>http://blog.vi-kan.net/2010/project-euler-problem-17/#comments</comments>
		<pubDate>Wed, 17 Nov 2010 22:01:37 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=251</guid>
		<description><![CDATA[After my success on getting unittest to work on the iPhone, I thought I should try it out some more. It&#8217;s been a while since last time I solved an Euler Problem, so maybe this would be a good excuse to solve another one? The last problems involved a lot of math, so this time [...]]]></description>
			<content:encoded><![CDATA[<p>After my success on <a title="UnitTesting on the iPhone" href="http://blog.vi-kan.net/2010/unittesting-on-the-iphone/" target="_self">getting unittest to work</a> on the iPhone, I thought I should try it out some more. It&#8217;s been a while since last time I solved an Euler Problem, so maybe this would be a good excuse to solve another one? The last problems involved a lot of math, so this time I found something completely different:</p>
<blockquote><p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.<br />
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p></blockquote>
<p>Well, lets see, then&#8230;</p>
<p><span id="more-251"></span><br />
We would need a class that can convert an integer into written words. I will call it WrittenNumber, and give it a class method +(NSString *)fromInt:(int) to do the work.</p>
<pre class="brush: objc; title: ;">@interface WrittenNumber : NSObject {
}
+(NSString *) fromInt:(int)number;
@end</pre>
<p>Now, that I got my basic interface in place, I tried it out with the most basic test:</p>
<pre class="brush: objc; title: ;">- (void)testSingleDigitOne {
    GHAssertEqualStrings([WrittenNumber fromInt:1], @&quot;one&quot;, nil);
}</pre>
<p>As expected, it failed :</p>
<pre class="brush: plain; title: ;">euler17/testSingleDigitOne ✘ 0.00s

	Name: GHTestFailureException
	File: /../euler17.m
	Line: 40
	Reason: '' should be equal to 'one'.</pre>
<p>I will not take you through every single step I took, including returning &#8216;one&#8217;, writing a new test and realize that returning &#8216;one&#8217; didn&#8217;t work for other cases and so on&#8230; What we need, is to identify every word that we need to build up every number from one to 1000. Up to nineteen, there are all unique words. From there, most written numbers are combined by two or more words. So I put these words into a couple of static arrays:</p>
<pre class="brush: objc; title: ;">static NSString * simpleNumbers[] = {
    @&quot;&quot;, @&quot;one&quot;, @&quot;two&quot;, @&quot;three&quot;, @&quot;four&quot;, @&quot;five&quot;, @&quot;six&quot;, @&quot;seven&quot;, @&quot;eight&quot;, @&quot;nine&quot;,
    @&quot;ten&quot;, @&quot;eleven&quot;, @&quot;twelve&quot;, @&quot;thirteen&quot;, @&quot;fourteen&quot;, @&quot;fifteen&quot;, @&quot;sixteen&quot;, @&quot;seventeen&quot;, @&quot;eighteen&quot;, @&quot;nineteen&quot;
}; 

static NSString *tens[] = {
    @&quot;&quot;, @&quot;&quot;, @&quot;twenty&quot;, @&quot;thirty&quot;, @&quot;forty&quot;, @&quot;fifty&quot;, @&quot;sixty&quot;, @&quot;seventy&quot;, @&quot;eighty&quot;, @&quot;ninety&quot;
};</pre>
<p>I have padded the &#8216;tens&#8217;-array to make indexing a little easier. tens[2] = &#8220;twenty&#8221;, tens[8] = &#8220;eighty&#8221; and so on. Now, the algorithm that I ended  up with, was to start with the larger part of the number, converting it into text, and then handle the rest in the same way. Peele away the larger part, convert it to text, and repeat.</p>
<pre class="brush: objc; title: ;">+(NSString *) processSimpleNumbers:(int)number
{
    return simpleNumbers[number];
}

+(NSString *) processTens:(int)number
{
    if (number &amp;lt; 20) {
        return [self processSimpleNumbers:number];
    }

    int div = number / 10;
    int rest = number % 10;
    NSString *tmp = tens[div];
    if (rest &amp;gt; 0){
        return [NSString stringWithFormat:@&quot;%@-%@&quot;, tmp, [self processSimpleNumbers:rest]];
    } else{
        return tmp;
    }
}

+(NSString *) processHundreds:(int)number;
{
    if (number &amp;lt; 100) {
        return [self processTens:number];
    }

    int div = number / 100;
    int rest = number % 100;
    NSString *tmp = [NSString stringWithFormat:@&quot;%@ hundred&quot;, simpleNumbers[div]];
    if (rest &amp;gt; 0){
        return [NSString stringWithFormat:@&quot;%@ and %@&quot;, tmp, [self processTens:rest] ];
    } else {
        return tmp;
    }
}

+(NSString *) processThousands:(int)number;
{
    if (number &amp;lt; 1000){
        return [self processHundreds:number];
    }

    int div = number / 1000;
    int rest = number % 1000;

    NSString *tmp = [NSString stringWithFormat:@&quot;%@ thousand&quot;, [self processHundreds:div]];

    if (rest &amp;gt; 0) {
        if (rest &amp;lt; 100) {
            return [NSString stringWithFormat:@&quot;%@ and %@&quot;, tmp, [self processTens:rest]];
        } else {
            return [NSString stringWithFormat:@&quot;%@ %@&quot;, tmp, [self processHundreds:rest]];
        }
    } else{
        return tmp;
    }
}

+(NSString *) fromInt:(int)number
{
    return [self processThousands:number];
}</pre>
<p>I&#8217;m sure there are prettier ways of solving this, but it works. The remaining task, is trivial. Convert each number and accumulate the length of the strings after removing hyphens and spaces. Of cause, we could get rid of these characters right away by not returning them in the first place, but then again, I did not&#8230;</p>
<p>I have uploaded the source to my <a href="http://svn.vi-kan.net/euler">svn repository</a> if you want to take a look. You&#8217;ll find the WrittenNumber class in the iPhone/src folder, and the unittests in the iPhone/tests folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/project-euler-problem-17/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 10</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-10/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-10/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 20:07:35 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-10/</guid>
		<description><![CDATA[Yet another problem involving primes. Guess I have to make a better prime generator soon… The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Soon, but not yet… Using the same generator from problem 7, I go [...]]]></description>
			<content:encoded><![CDATA[<p>Yet another problem involving primes. Guess I have to make a better prime generator soon…</p>
<blockquote><p>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</p>
<p>Find the sum of all the primes below two million.</p></blockquote>
<p><span id="more-144"></span></p>
<p>Soon, but not yet…</p>
<p>Using the same generator from <a title="Find the 10001st prime" href="http://blog.vi-kan.net/2009/project-euler-problem-7/" target="_blank">problem 7</a>, I go for an easy, but slow, solution for this one. There is one thing, though. Our generator generates up to the nth prime, but in this problem, we need to find every prime below 2000000. Already decided not to make a new prime generator, we cheat by asking it generate a lot of primes, and then jump out as soon as we hit a prime to big.</p>
<pre class="brush: delphi; title: ;">sum := 0;for prime in PrimeGenerator(500000) do
begin
  if prime &amp;gt;= 2000000 then
    break;
  sum := sum + prime;
end;</pre>
<p>I choose to generate 500000 primes, pretty sure one prime out of four should be enough.</p>
<p>And that&#8217;s it – it’s all there at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-10/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 9</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-9/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-9/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 21:45:13 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=134</guid>
		<description><![CDATA[On our way to Lofoten last weekend, my wife and I had a small brainstorming on problem no. 9: A Pythagorean triplet is a set of three natural numbers, a &#60; b &#60; c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There [...]]]></description>
			<content:encoded><![CDATA[<p>On our way to Lofoten last weekend, my wife and I had a small brainstorming on problem no. 9:</p>
<blockquote><p>A Pythagorean triplet is a set of three natural numbers, a &lt; b &lt; c, for which,</p>
<p><em>a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup></em></p>
<p>For example, 3<sup>2</sup> + 4<sup>2</sup> = 9 + 16 = 25 = 5<sup>2</sup>.</p>
<p>There exists exactly one Pythagorean triplet for which a + b + c = 1000.<br />
Find the product <em>abc</em>.</p></blockquote>
<p><span id="more-134"></span></p>
<p>Both of us agreed there had to be some kind of mathematical formula for this kind of problem. The problem, though, was that non of us new this formula, and there wasn’t that many math books in the car that day… So instead of trying to guess the magic formula, we tried to optimize the search for the right numbers.</p>
<p>We could put three for loops inside each other, scanning the numbers from 1 to 1000 for each. Trying 1 + 1 + 1 as a possible solution isn’t that clever, though. Neither is the combination 1000 + 1000 + 1000.</p>
<p>Let’s take a look at the maximum possible values for <em>a</em>, <em>b</em> and <em>c</em>. The fact that <em>a</em> &lt; <em>b</em> &lt; <em>c</em> makes this kind of easy.  Since all three numbers must be positive, <em>c</em> can’t be larger than 997 to make room for <em>a</em> = 1 and <em>b</em> = 2. The number <em>b</em> can’t be larger than 499, which makes room for a = 1 and c = 500. And finally, <em>a</em> can’t be larger than 332, which makes room for <em>b</em> = 333 and <em>c</em> = 335.</p>
<pre class="brush: delphi; title: ;">    for a := 1 to 332 do
      for b := a+1 to 498 do
        for c := b+1 to 998 do
        begin
          ...
        end;</pre>
<p>Now, the test it self should be easy:</p>
<pre class="brush: delphi; title: ;">if (a + b + c = 1000) and (a*a + b*b = c*c) then
  ...</pre>
<p>We can do one more easy optimization. I our current <em>c</em> makes for a larger sum than 1000, we can break out of the innermost loop. This actually saves us a lot of cycles.</p>
<pre class="brush: delphi; title: ;">        for c := b+1 to 998 do
        begin
          sum := a + b + c;
          if (sum) &amp;gt; 1000 then
            break;

          if (sum = 1000) and (a*a + b*b = c*c) then
          begin
            ...
          end;
        end;</pre>
<p>And that’s it. The complete solution is available as usual. Check it out at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 8</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-8/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-8/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 21:17:25 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-8/</guid>
		<description><![CDATA[A couple of days ago, I solved eulers problem no. 8. I finally found some time to blog about my solution. Find the greatest product of five consecutive digits in the 1000-digit number. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 I can’t [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago, I solved eulers problem no. 8. I finally found some time to blog about my solution. </p>
<blockquote><p>Find the greatest product of five consecutive digits in the 1000-digit number. </p>
<p>73167176531330624919225119674426574742355349194934      <br />96983520312774506326239578318016984801869478851843       <br />85861560789112949495459501737958331952853208805511       <br />12540698747158523863050715693290963295227443043557       <br />66896648950445244523161731856403098711121722383113       <br />62229893423380308135336276614282806444486645238749       <br />30358907296290491560440772390713810515859307960866       <br />70172427121883998797908792274921901699720888093776       <br />65727333001053367881220235421809751254540594752243       <br />52584907711670556013604839586446706324415722155397       <br />53697817977846174064955149290862569321978468622482       <br />83972241375657056057490261407972968652414535100474       <br />82166370484403199890008895243450658541227588666881       <br />16427171479924442928230863465674813919123162824586       <br />17866458359124566529476545682848912883142607690042       <br />24219022671055626321111109370544217506941658960408       <br />07198403850962455444362981230987879927244284909188       <br />84580156166097919133875499200524063689912560717606       <br />05886116467109405077541002256983155200055935729725       <br />71636269561882670428252483600823257530420752963450</p>
</blockquote>
<p> <span id="more-132"></span>
<p>I can’t see any smart solution for this problem. A simple brute force scan through the series of digits will have to do. </p>
<p>I start out with the number as a string. That makes it easy to loop through digit by digit.&#160; To make it even easier, I have made an array of five bytes that I place ‘over’ the current character. This gives me a ‘view’ of the five current digits that needs to be multiplied as bytes instead of characters. </p>
<pre class="brush: delphi; title: ;">const
  SUBJECT = '73167176531330624919225119674426574742355349 .... 57530420752963450';

type
  PFiveDigits = ^TFiveDigits;
  TFiveDigits = array[0..4] of byte;

begin
  for I := 1 to length(Subject) - 6 do
  begin
    FiveDigits := @SUBJECT[i];
  end;
end;</pre>
<p>A character in the range 0 to 9 has byte value in the range of 48 to 57. Before we multiply the values, we have to normalize them. We can do that by subtracting 48 from each byte value.</p>
<pre class="brush: delphi; title: ;">const
  NULLCHAR = ord('0');
  ...
  present := (FiveDigits[0]-NULLCHAR) * (FiveDigits[1]-NULLCHAR) * (FiveDigits[2]-NULLCHAR) * (FiveDigits[3]-NULLCHAR) * (FiveDigits[4]-NULLCHAR);</pre>
<p>Now we just have to keep track of the highest produced product do find the answer.</p>
<pre class="brush: delphi; title: ;">    largest := 0;
    for I := 1 to length(Subject) - 6 do
    begin
      FiveDigits := @SUBJECT[i];
      present := (FiveDigits[0]-NULLCHAR) * (FiveDigits[1]-NULLCHAR) * (FiveDigits[2]-NULLCHAR) * (FiveDigits[3]-NULLCHAR) * (FiveDigits[4]-NULLCHAR);
      if present &amp;gt; largest then
      begin
        largest := present;
        position := i;
      end;
    end;</pre>
<p>As usual, you will find the code at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-8/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 7</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-7/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-7/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 09:37:26 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-7/</guid>
		<description><![CDATA[It want be easy to keep up with my brother on this. Well, here’s my take on Project Eulers problem no 7: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? Algorithms conserning primes is [...]]]></description>
			<content:encoded><![CDATA[<p>It want be easy to keep up with <a href="http://www.geekality.net/2009/09/24/project-euler-problem-7/">my brother</a> on this. Well, here’s my take on Project Eulers problem no 7:</p>
<blockquote><p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6<sup>th</sup> prime is 13. </p>
<p>What is the 10001<sup>st</sup> prime number?</p>
</blockquote>
<p> <span id="more-108"></span>
<p>Algorithms conserning primes is a large and complex field. I guess the are many different solutions to this problem, so the question will be how efficient the one that I find will be.</p>
<p>One thing is for sure, though. We need a way of finding primes. As far as I know, there is no formula to find the n<sup>th</sup> prime. We have to find the first 10 000 primes first before we can find our wanted one. </p>
<h2>A Prime Generator</h2>
<p>I will use a <a href="http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-6-generators.html">enumerator-pattern</a> for our prime generator. For that, we will need two classes. First we will need a factory-class that implements the GetEnumerator function. Then we will need the class that handles the actual enumeration.</p>
<pre class="brush: delphi; title: ;">type
  TPrimeGenerator = class
  public
    function GetCurrent: extended;
    function MoveNext: boolean;
    property Current: extended read GetCurrent;
  end;

  TPrimeGeneratorFactory = class
  public
    function GetEnumerator: TPrimeGenerator;
  end;</pre>
<p>With this implementation, we will be allowed to write code like this:</p>
<pre class="brush: delphi; title: ;">for prime in TPrimeGeneratorFactory.Create do
begin
  ...
end;</pre>
<p>This code would generate an awful lot of primes, though. It would be nice to give it some kind limit. We can add that to the constructor, and check in the MoveNext method if the limit is reached. We would also need some live-time management on both the factory and the generator. The generator it self can be created and destroyed by the factory, but we can also make it easier by letting the factory implement an interface. If we do, delphi will manage it’s lifetime for us. </p>
<pre class="brush: delphi; title: ;">type
  TPrimeGenerator = class
  public
    constructor Create(numberOfPrimes: integer);
    ...
  end;

  IPrimeGeneratorFactory = interface
    function GetEnumerator: TPrimeGenerator;
  end;

  TPrimeGeneratorFactory = class(TInterfacedObject, IPrimeGeneratorFactory)
  public
    constructor Create(numberOfPrimes: integer);
    destructor Destroy; override;
  end;

  function PrimeGenerator(numberOfPrimes: integer): IPrimeGeneratorFactory;</pre>
<p>Now, we can rewrite our for … in – loop, and just get the number of primes that we want. We will know longer have any leaks either.</p>
<pre class="brush: delphi; title: ;">for prime in PrimeGenerator(10001) do
begin
  ...
end;</pre>
<h2>Finding Primes</h2>
<p>Our generator doesn’t actually generate primes yet, though. Let’s see if we can make it do so. So how do we find primes? What is a prime? Wikipedia gives us the following definition of <a href="http://en.wikipedia.org/wiki/Prime_number">prime numbers</a>:</p>
<blockquote>
<p>In mathematics, a prime number (or a prime) is a natural number which has exactly two distinct natural number divisors: 1 and itself. </p>
</blockquote>
<p>So if we loop through all numbers, and test if it’s possible to devide it by any other number, we should have our primes. The problem is, though, that this takes time. A lot of time. We have to find a way of shortening down the ammount of numbers we need to check. The first thing we should remove, is all even numbers. Every single even number is divisible by the number 2, so they can’t be primes. Except for the number 2 it self – it’s a prime, cause has only two divisors: 1 and itself.</p>
<p>Since 2 is the first prime number, it would be an easy exception to handle, and we have effectively cut shortened down possible primes to the half of what we started with.</p>
<p>Let’s write our FindNextPrime method:</p>
<pre class="brush: delphi; title: ;">function TPrimeGenerator.FindNextPrime(PreviousPrimeFound: extended): extended;
var
  found: boolean;
  currentNumber: extended;
begin
  currentNumber := PreviousPrimeFound;
  repeat
    if (CurrentNumber = 1) or (currentNumber = 2) then
    begin
      currentNumber := currentNumber + 1;
      result := true;
    end
    else
    begin
      currentNumber := currentNumber + 2;
      found := CheckIfPrime(currentNumber);
    end;
  until found;

  result := currentNumber;
end;</pre>
<p>We here assume that PreviousPrimeFound equals 1 when no previous prime is found. So if the previous prime is 1 or 2, we just increment by one, knowing that both 2 and 3 is prime numbers, and signal a successfull found. If previous prime was not 1 or 2, it has to be 3 or any other odd number, so we increment by two to skip even numbers. </p>
<p>Let’s take a look at the CheckIfPrime( ) method. How do we check if a number is divisible by any other number? I guess we have to check:</p>
<pre class="brush: delphi; title: ;">function TPrimeGenerator.CheckIfPrime(number: integer): boolean;
var
  i: integer;
begin
  result := true;
  for i := 2 to number - 1 do
  begin
    if number mod i = 0 then
    begin
      result := false;
      break;
    end;
  end;
end;</pre>
<p>Can you see a bottleneck here? For every number we test, there is one more number to devide. How can we optimize this?</p>
<p>First of all, every natural number can be expressed as a product of primes. 12 = 2 x 2 x 3, 20 = 2 x 2 x 5 and so on. So if a number is divisible by a non prime number, it should also be divisible by a prime number. So if we can find a way of just dividing by primes we would speed up things a lot.</p>
<p>So let’s add a list of previous found primes to the generator class, and loop through that list instead of all numbers.</p>
<pre class="brush: delphi; title: ;">function TPrimeGenerator.CheckIfPrime(number: extended): boolean;
var
  itr: DIterator;
  prevPrime: extended;
  found: boolean;
begin
  found := false;
  itr := FPrimes.start;
  while IterateOver(itr) do
  begin
    prevPrime := getExtended(itr);

    if Frac(number / prevPrime) = 0 then
    begin
      found := true;
      break;
    end;
  end;

  result := not found;
end;</pre>
<p>This makes things a lot faster, but I think we still can gain something. In the same wikipedia article that I refered to earlier, it is sufficient to test primes smaller than the sqaure root of the number we are currently testing. So let’s add that to our loop:</p>
<pre class="brush: delphi; title: ;">function TPrimeGenerator.CheckIfPrime(number: extended): boolean;
var
  itr: DIterator;
  prevPrime: extended;
  found: boolean;
  root: extended;
begin
  root := sqrt(number);
  ...
  while IterateOver(itr) do
  begin
    prevPrime := getExtended(itr);
    if prevPRime &amp;gt; root then
      break;

    if ...
  end;
  ...
end;</pre>
<h2>The Solution</h2>
<p>Just like the solution for problem 6, you can find the complete code at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. It gives the answer in about 40-50 ms.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 6</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-6/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-6/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 20:40:10 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=97</guid>
		<description><![CDATA[Inspired by my brother over at geekality.net, I thought I should do an attempt on the various problems presented at projecteuler.net/.  Since he already solved the first five, I jumped right in at problem 6: The sum of the squares of the first ten natural numbers is, 12 + 22 + &#8230; + 102 = [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by my brother over at <a href="http://www.geekality.net/" target="_blank">geekality.net</a>, I thought I should do an attempt on the various problems presented at <a title="http://projecteuler.net/" href="http://projecteuler.net/">projecteuler.net/</a>.  Since he already solved the first five, I jumped right in at <a href="http://projecteuler.net/index.php?section=problems&amp;id=6" target="_blank">problem 6</a>:</p>
<blockquote>
<p align="left">The sum of the squares of the first ten natural numbers is,</p>
<p align="center">1<sup>2</sup> + 2<sup>2</sup> + &#8230; + 10<sup>2</sup> = 385</p>
<p align="left">The square of the sum of the first ten natural numbers is,</p>
<p align="center">(1 + 2 + &#8230; + 10)<sup>2</sup> = 552 = 3025</p>
<p align="left">Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is</p>
<p align="center">3025  385 = 2640.</p>
<p>Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</p></blockquote>
<p><span id="more-97"></span></p>
<p>This problem has two distinct parts. First, there is the sum of a sequence of the squared natural numbers, then there is the sum of a sequence of natural numbers, squared.</p>
<h2>Sum of a series of squared natural numbers</h2>
<p>The problem tells to summarize the square of the first hundred natural numbers. That gives us the following sequence:</p>
<p align="center">1<sup>2</sup> + 2<sup>2</sup> + &#8230; 99<sup>2</sup> + 100<sup>2</sup></p>
<p align="left">The simplest solution would be a brute force loop like this one:</p>
<pre class="brush: delphi; title: ;">function sumSquaredNumbers( ): longword;
var
  i: integer;
begin
  result := 0;
  for i := 1 to 100 do
    result := result + (power(i, 2));
end;</pre>
<p>That wouldn’t be much fun, though. There has to be a more general, optimized algorithm for this kind of work. First of all, we should make the function workable for any series length. That should be easy – just switch the hardcoded 100 with an given parameter:</p>
<pre class="brush: delphi; title: ;">function sumSquaredNumbers(serieslength: integer): longword;
var   i: integer;
begin
  for i := 1 to seriesLength do
    result := …
end;</pre>
<p>But the code is still the same, though. Nothing was optimized in any way. We still have the loop, making our function <a href="http://en.wikipedia.org/wiki/Linear_time" target="_blank">linear</a>.</p>
<p>Google to the rescue!</p>
<p><a href="http://www.math.com">math.com</a> have a nice section on Series Expansions, which includes a table of <a href="http://www.math.com/tables/expansion/power.htm" target="_blank">power summations</a>. This table states that</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td colspan="4" valign="top">n</td>
</tr>
<tr>
<td valign="vcenter"><span>∑</span></td>
<td valign="top">k<sup>2</sup></td>
<td valign="vcenter">= 1 + 4 + 9 + &#8230; + n<sup>2</sup></td>
<td valign="vcenter">= (1/3)n<sup>3</sup> + (1/2)n<sup>2</sup> + (1/6)n</td>
</tr>
<tr>
<td colspan="4" valign="top">k=1</td>
</tr>
</tbody>
</table>
</blockquote>
<p>Why this should be true, I honestly can’t tell, but a fast comparison to our brute force solution shows that it gives us the right numbers. That’s good enough for now:</p>
<pre class="brush: delphi; title: ;">function sumSquaredNumbers(seriesLength: integer): longword;
begin
  result := trunc(
                ((1/3) * power(seriesLength, 3))
              + ((1/2) * power(seriesLength, 2))
              + ((1/6) * seriesLength)
              );
end;</pre>
<p>I think this is a nice solution, and a <a href="http://en.wikipedia.org/wiki/Constant_time">constant one</a> as well. It doesn’t matter if the series is of length one, hundred or thousand – the computation should take the same amount of time.</p>
<h2>Sum of a series of natural numbers, squared</h2>
<p>This part should be a lot easier. We could start with a brute force solution to this part too, but I think we could come up with something smarter right away.</p>
<p>I already know of a simple optimization. If you add the first and last number in the series, you will get the same as if you add the second and next to last number:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="145" align="center">
<tbody>
<tr>
<td width="13" valign="top"></td>
<td width="20" valign="top">1</td>
<td width="20" valign="top">2</td>
<td width="20" valign="top">3</td>
<td width="20" valign="top">4</td>
<td width="20" valign="top">5</td>
<td width="6" valign="top">6</td>
<td width="6" valign="top">7</td>
<td width="6" valign="top">8</td>
<td width="6" valign="top">9</td>
<td width="6" valign="top">10</td>
</tr>
<tr>
<td width="13" valign="top">+</td>
<td width="20" valign="top">10</td>
<td width="20" valign="top">9</td>
<td width="20" valign="top">8</td>
<td width="20" valign="top">7</td>
<td width="20" valign="top">6</td>
<td width="6" valign="top">5</td>
<td width="6" valign="top">4</td>
<td width="6" valign="top">3</td>
<td width="6" valign="top">2</td>
<td width="6" valign="top">1</td>
</tr>
<tr>
<td width="13" valign="top">=</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
</tr>
</tbody>
</table>
</blockquote>
<p>As you can see, every pair of numbers makes the same sum when added together. So for any given series, you can take the first and the last number and add them together, then you can multiply the sum by the length of the series, and finally divide by two.</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td colspan="4" valign="top">n</td>
</tr>
<tr>
<td valign="vcenter"><span>∑</span></td>
<td valign="top">k</td>
<td valign="vcenter">= 1 + 2 + 3 + &#8230; + n</td>
<td valign="vcenter">= (1 + n) * n / 2</td>
</tr>
<tr>
<td colspan="4" valign="top">k=1</td>
</tr>
</tbody>
</table>
</blockquote>
<p>I know there are other solutions to this, but this one will do.</p>
<pre class="brush: delphi; title: ;">function sumSquared(seriesLength: longword): longword;
begin
  result := trunc(power(((1 + seriesLength) * seriesLength / 2), 2));
end;</pre>
<h2>The solution</h2>
<p>Now that we have solved each of the two sub parts of the problem, I guess we’re ready to solve the main thing.</p>
<blockquote><p>Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</p></blockquote>
<p>Since we know the sum of the squares, and we now the square of the sum, it’s just a matter of substract the one from the other:</p>
<pre class="brush: delphi; title: ;">function diff(serieslength: longword): longword;
begin
  result := sumSquared(serieslength) - sumSquaredNumbers(serieslength);
end;</pre>
<p>I have uploaded my complete solution to <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. The code also contains a simple stopwatch to time the code. This code is so simple, though, that it’s hard to get any measures.</p>
<p>And that’s it. Let’s see if we can solve the next one too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-6/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
