<?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>Stefano Ricciardi &#187; algorithm</title>
	<atom:link href="http://stefanoricciardi.com/tag/algorithm/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Tue, 15 Nov 2011 07:57:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Project Euler Problem 18 in F#</title>
		<link>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/</link>
		<comments>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/#comments</comments>
		<pubDate>Mon, 10 Jan 2011 12:18:39 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1317</guid>
		<description><![CDATA[2011 brings us yet another Project Euler problem to tackle: this time is&#160;Problem 18,&#160;one of the most interesting that I&#39;ve solved so far: 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. 3 7 4 2 4 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>2011 brings us yet another Project Euler problem to tackle: this time is&nbsp;<a href="http://projecteuler.net/index.php?section=problems&amp;id=18">Problem 18</a>,&nbsp;one of the most interesting that I&#39;ve solved so far:</p>
<blockquote>
<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 align="center"><b>3</b> <br />
		<b>7</b> 4 <br />
		2 <b>4</b> 6 <br />
		8 5 <b>9</b> 3</p>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<p align="center">75 <br />
		95 64 <br />
		17 47 82 <br />
		18 35 87 10 <br />
		20 04 82 47 65 <br />
		19 01 23 75 03 34 <br />
		88 02 77 73 07 63 67 <br />
		99 65 04 28 06 16 70 92 <br />
		41 41 26 56 83 40 80 70 33 <br />
		41 48 72 33 47 32 37 16 94 29 <br />
		53 71 44 65 25 43 91 52 97 51 14 <br />
		70 11 33 28 77 73 17 78 39 68 17 57 <br />
		91 71 52 38 17 14 91 43 58 50 27 29 48 <br />
		63 66 04 68 89 53 67 30 73 16 69 87 40 31 <br />
		04 62 98 27 23 09 70 98 73 93 38 53 60 04 23</p>
<p><small><b>NOTE:</b> As there are only 16384 routes, it is possible to solve this problem by trying every route. However, <a href="http://projecteuler.net/index.php?section=problems&amp;id=67">Problem 67</a>, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) </small></p>
</blockquote>
<h2>Analysis</h2>
<p>This problem is easily solved resorting to <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic programming</a>, which we can loosely describe as decomposing the overall problem into easier sub-problems and combining their solutions to find the final answer.</p>
<p>In our case, if we consider the number associated with each node of the triangle as a cost, the overall problem can be expressed as<em> finding the path with maximum cost from the upper vertex to the bottom row</em>. A generic sub-problem would be the cost to reach the bottom row from a generic node at position <em>i,j</em>.</p>
<p>Given the cost <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-4faccce819a35988e3ddcb44c2ac6908_l3.png" class="ql-img-inline-formula" alt="&#99;&#95;&#123;&#105;&#44;&#106;&#125;" title="Rendered by QuickLaTeX.com" style="vertical-align: -6px;"/> of passing through a given node and the cost <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-b5bf03ee0efde0ed83151b123ead9d6d_l3.png" class="ql-img-inline-formula" alt="&#67;&#95;&#123;&#105;&#44;&#106;&#125;" title="Rendered by QuickLaTeX.com" style="vertical-align: -6px;"/> of reaching the bottom row from that particular node, we can define the following truth:</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 19px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-ee11802d95580493d2bf20d7eeb2bf0e_l3.png"class="ql-img-displayed-equation" alt="&#92;&#91;&#67;&#95;&#123;&#105;&#44;&#106;&#125;&#32;&#61;&#32;&#99;&#95;&#123;&#105;&#44;&#106;&#125;&#32;&#43;&#32;&#109;&#97;&#120;&#40;&#67;&#95;&#123;&#105;&#43;&#49;&#44;&#106;&#125;&#44;&#32;&#67;&#95;&#123;&#105;&#43;&#49;&#44;&#106;&#43;&#49;&#125;&#41;&#92;&#93;" title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>or, in other words, from each node <em>i,j</em>&nbsp;the cost of reaching the bottom is equal to the cost of the node itself plus the maximum path between one of the two adjacent nodes from the row below.</p>
<p>Let&#39;s confirm why this is the case with the help of the following figure: consider for example the first node from the left in the fourteenth (last-but-one) row (having cost <strong>63</strong>): from there you can move to the bottom either going to node <strong>04</strong> or node <strong>62</strong>. Clearly, if we want to pick the highest cost, we need to pick <strong>62 </strong>(and we mark this choice with a grey line). The overall cost to reach the bottom from that node is thus 63 + max (04, 62) = <strong>125</strong>.</p>
<p>Let&rsquo;s consider now the second node from that row (<strong>66)</strong>. From there, we have to choose between node <strong>62</strong> and <strong>98</strong>: the highest cost path from there is thus 66 + max(62, 98) = <strong>164</strong>. We can continue for all the nodes in the row to find the highest cost path from each node; the solution to such sub-problems is indicated in gray close to each node.</p>
<p><a href="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows.png"><img alt="ProjectEuler18_2rows" border="0" height="89" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows_thumb.png" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ProjectEuler18_2rows" width="454" /></a></p>
<p>Having solved all sub-problems for row 14, we can now consider the row immediately above. In the following figure, I have replaced row 14 with the solutions of the sub-problems that we had just solved; the row above is row 13. Please note how we don&rsquo;t care about row 15 anymore: its contribution to the overall problem is already captured in each sub-problems&rsquo; solution for row 14! Hence, we proceed in a similar way to solve the sub-problems for the row 13 just as we did for row 14:</p>
<p><a href="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows1.png"><img alt="ProjectEuler18_2rows" border="0" height="68" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows_thumb1.png" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ProjectEuler18_2rows" width="529" /></a></p>
<p>We continue to follow a similar pattern moving upwards row after row, until we reach the tip of the triangle, always considering two rows at a time.</p>
<h2>Solution</h2>
<pre class="brush:fsharp">#light

let a = Array2D.zeroCreate&lt;int&gt; 15 15

a.[0,0] &lt;- 75
a.[1,0] &lt;- 95
a.[1,1] &lt;- 64
a.[2,0] &lt;- 17
a.[2,1] &lt;- 47
a.[2,2] &lt;- 82
a.[3,0] &lt;- 18
// other initializations omitted for clarity
// full listing available on Github
// (https://github.com/stefanoric/YAPEFSHARP)
a.[14,10] &lt;- 38
a.[14,11] &lt;- 53
a.[14,12] &lt;- 60
a.[14,13] &lt;- 04
a.[14,14] &lt;- 23 

let costs = Array2D.zeroCreate&lt;int&gt; 15 15

// costs for bottom row is the same as bottom row values
Array2D.blit a 14 0 costs 14 0 1 15 |&gt; ignore

let max a b = if a &gt; b then a else b

for i in 13 .. -1 .. 0 do
    for j in 0 .. i do
        costs.[i,j] &lt;- a.[i,j] + max costs.[i+1,j] costs.[i+1, j+1]

let result () =
    costs.[0,0]</pre>
<p>Most of the code for this solution is needed just to initialize the two dimensional array containing the triangle. For reading convenience, I have skipped most of the uninteresting rows, but you can find the complete solution on <a href="https://github.com/stefanoric/YAPEFSHARP">Github</a>.</p>
<p>So, we have a matrix (2D array) for the cost of each nodes and another matrix for the solutions of the sub-problems associated to each node. Trivially, the costs and the solutions coincide for the bottom row (note the handy <code>Array2D.blit</code> function to copy a whole row from one matrix to the other).</p>
<p>Then, with a loop we move backward from the last-but-one row up to the tip of the triangle calculating the sub-problems solutions as explained above.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-18-in-F-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 17 in F#</title>
		<link>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 15:33:52 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1296</guid>
		<description><![CDATA[   ]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Project Euler problem 17 turned out to be quite an easy one.</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.</p>
<p>If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p>
<p><small>NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of &quot;and&quot; when writing out numbers is in compliance with British usage.</small></p>
</blockquote>
<h2>Solution</h2>
<p>The solution this time is almost trivial:</p>
<ul>
<li>&quot;<em>Zero</em>&quot; is considered to have 0 length (it will be obvious later on why this is the case)</li>
<li>Numbers from <strong>1</strong> to <strong>19</strong> have their own unique names (i.e. they are not composed by putting together more words)</li>
<li>Numbers from <strong>20</strong> to<strong> 99</strong> are combined putting together a word like &quot;<em>thirty</em>&quot; and a number from 0 to 9. If the number is zero, we don&#39;t add anything (we don&#39;t say <em>&quot;twenty and zero&quot;</em>)</li>
<li>Numbers from <strong>100 </strong>to <strong>999 </strong>are combined putting together a words like &quot;<em>two hundred and</em>&quot; plus a number from 0 to 99 composed as explained above. Exact multiples of <strong>100 </strong>are exception in that they don&#39;t have another trailing number (again, we don&#39;t say &quot;<em>two hundred and zero</em>&quot;).</li>
</ul>
<pre class="brush:fsharp">#light

let thousand    = &quot;oneThousand&quot;
let hundred     = &quot;hundred&quot;
let hundred_and = &quot;hundredAnd&quot;

let zero_to_nine = new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
zero_to_nine.[0] &lt;- &quot;&quot;
zero_to_nine.[1] &lt;- &quot;one&quot;
zero_to_nine.[2] &lt;- &quot;two&quot;
zero_to_nine.[3] &lt;- &quot;three&quot;
zero_to_nine.[4] &lt;- &quot;four&quot;
zero_to_nine.[5] &lt;- &quot;five&quot;
zero_to_nine.[6] &lt;- &quot;six&quot;
zero_to_nine.[7] &lt;- &quot;seven&quot;
zero_to_nine.[8] &lt;- &quot;eight&quot;
zero_to_nine.[9] &lt;- &quot;nine&quot;

let ten_to_nineteen =  new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
ten_to_nineteen.[10] &lt;- &quot;ten&quot;
ten_to_nineteen.[11] &lt;- &quot;eleven&quot;
ten_to_nineteen.[12] &lt;- &quot;twelve&quot;
ten_to_nineteen.[13] &lt;- &quot;thirteen&quot;
ten_to_nineteen.[14] &lt;- &quot;fourteen&quot;
ten_to_nineteen.[15] &lt;- &quot;fifteen&quot;
ten_to_nineteen.[16] &lt;- &quot;sixteen&quot;
ten_to_nineteen.[17] &lt;- &quot;seventeen&quot;
ten_to_nineteen.[18] &lt;- &quot;eighteen&quot;
ten_to_nineteen.[19] &lt;- &quot;nineteen&quot;

let twenty_to_ninety = new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
twenty_to_ninety.[20] &lt;- &quot;twenty&quot;
twenty_to_ninety.[30] &lt;- &quot;thirty&quot;
twenty_to_ninety.[40] &lt;- &quot;forty&quot;
twenty_to_ninety.[50] &lt;- &quot;fifty&quot;
twenty_to_ninety.[60] &lt;- &quot;sixty&quot;
twenty_to_ninety.[70] &lt;- &quot;seventy&quot;
twenty_to_ninety.[80] &lt;- &quot;eighty&quot;
twenty_to_ninety.[90] &lt;- &quot;ninety&quot;

let len s = String.length s

let calculate_letters_under_one_hundred n =
    match n with
        | x when x &lt; 10 -&gt; len zero_to_nine.[x]
        | x when x &lt; 20 -&gt; len ten_to_nineteen.[x]
        | x when x &lt; 100 -&gt; len twenty_to_ninety.[((x / 10) * 10)] + len zero_to_nine.[(x % 10)]
        | _ -&gt; failwith &quot;Number is too big!&quot;

let calculate_letters n =
    match n with
        | x when x &lt; 100 -&gt; calculate_letters_under_one_hundred x
        | x when ((x &lt; 1000) &amp;&amp; (x % 100 = 0)) -&gt; len zero_to_nine.[(x / 100)] + len hundred
        | x when x &lt; 1000 -&gt; len zero_to_nine.[(x / 100)] + len hundred_and +  calculate_letters_under_one_hundred (x % 100)
        | 1000 -&gt; len thousand
        | _ -&gt; failwith &quot;Numer is too big!&quot;

let all_letters_up_to n =
    List.sumBy (fun i -&gt; calculate_letters i) [1..n]
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-17-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F" style="border:0px" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 16 in F#</title>
		<link>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/#comments</comments>
		<pubDate>Sun, 12 Dec 2010 14:10:15 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1282</guid>
		<description><![CDATA[It&#8217;s time for another Project Euler exercise. This time around it&#8217;s problem 16: 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? Analysis I have tried to found an elegant way to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>It&rsquo;s time for another Project Euler exercise. This time around it&rsquo;s problem 16:</p>
<blockquote>
<p>2<sup>15</sup> = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.</p>
<p>What is the sum of the digits of the number 2<sup>1000</sup>?</p>
</blockquote>
<h2>Analysis</h2>
<p>I have tried to found an elegant way to solve this problem at a mathematical level, but I couldn&#39;t gain any insight relating powers of 2 to their representation in base 10 (I&#39;d love to know if such a thing exists). Therefore I resorted to solve this problem with brute force.</p>
<p>Luckily F# (and now all other .NET 4.0 cousin languages) sports the<code> BigInteger</code> numeric type which helps tackling such huge numbers.</p>
<p>There are basically two approaches to solve this problem:</p>
<ul>
<li>Transform the result of exponentiation into a <em>string </em>and iterate through the string adding up all the individual digits, or</li>
<li>Do without strings, and decompose the big number into the individual digits on my own.</li>
</ul>
<p>I have decided to take the second route because it seemed like a more interesting exercise (the first approach could probably lead to a one-liner). <sup>[<a href="#project-euler-problem-16-in-f-n-1" class="footnoted" id="to-project-euler-problem-16-in-f-n-1">1</a>]</sup>.</p>
<p>Let&rsquo;s consider a generic number <em>n</em> and consider how we can describe it as a sum of powers of 10:</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 53px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-4ea1e3a6cdfb46f446deea4ce5faa1a1_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#91; &#110;&#32;&#61;&#32;&#92;&#115;&#117;&#109;&#95;&#123;&#105;&#61;&#48;&#125;&#94;&#107;&#32;&#100;&#95;&#105;&#49;&#48;&#94;&#105; &#92;&#93; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>For example</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 18px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-fa02da8a8e9cec89a5809289b7db483e_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#91;&#32;&#52;&#50;&#51;&#32;&#61;&#32;&#51;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#48;&#32;&#43;&#32;&#50;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#49;&#32;&#43;&#32;&#52;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#50;&#32;&#92;&#93; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>and <em>k = 2,</em> <em>d<sub>0</sub> = 3</em>, <em>d<sub>1</sub> = 2</em>, and <em>d<sub>2</sub> = 4</em></p>
<p>&nbsp;</p>
<p>So, given a generic number <em>n</em>, we need to find the highest power of ten ( <em>k </em>) such that <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-c669e5dc42c92019f21d9a504d0c86b9_l3.png" class="ql-img-inline-formula" alt="&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#110;&#125;&#123;&#49;&#48;&#94;&#107;&#125;&#32;&#62;&#32;&#48;" title="Rendered by QuickLaTeX.com" style="vertical-align: -8px;"/></p>
<p>(logarithms will help us there). After <em>k</em> is found, we can start diving n by <em>10<sup>k</sup></em> to find <em>d<sub>k</sub> </em>and use the reminder of the division to calculate <em>d<sub>k-1</sub></em> and so forth until we reach <em>d<sub>0</sub></em>.</p>
<h2>Solution</h2>
<pre class="brush:fsharp">#light

open System
open System.Numerics

let rec decompose_rec n power_of_ten accu =
    match power_of_ten with
        | i when i = 1I -&gt; accu @ [n]
        |_ -&gt;
            let d = n / power_of_ten
            let digits = accu @ [d]
            decompose_rec (n - (d * power_of_ten)) (power_of_ten / 10I) digits

let decompose n =
    let power = floor (log10 (float n))
    let initial_power_of_ten = BigInteger.Pow(10I, int32 power)
    decompose_rec n initial_power_of_ten []

let sum_digits n =
    decompose n |&gt; List.sum
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-16-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F" style="border:0px" /></a></p>

<ol class="footnotes">
	<li class="footnote" id="project-euler-problem-16-in-f-n-1"><strong><sup>[1]</sup></strong> A recruiter for a very big company once asked me something very similar during an interview as a coding exercise <a class="note-return" href="#to-project-euler-problem-16-in-f-n-1">&#x21A9;</a></li></ol>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 12 in F#</title>
		<link>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/</link>
		<comments>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 12:40:54 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1187</guid>
		<description><![CDATA[   ]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>After a brief digression with an <a href="http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/">RPN Calculator</a>, here we are again with a new Project Euler problem:</p>
<blockquote><p>The sequence of triangle numbers is generated by adding the natural numbers.</p>
<p>So the 7^(th) triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.</p>
<p>The first ten terms would be: <br />
		1, 3, 6, 10, 15, 21, 28, 36, 45, 55, &#8230;</p>
<p>Let us list the factors of the first seven triangle numbers:</p>
<p>
	1: 1 <br />
	3: 1,3 <br />
	6: 1,2,3,6 <br />
	10: 1,2,5,10 <br />
	15: 1,3,5,15 <br />
	21: 1,3,7,21 <br />
	28: 1,2,4,7,14,28</p>
<p>We can see that 28 is the first triangle number to have over five divisors.</p>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p>Again, this problem is relatively simple to solve and it&#39;s about finding an algorithm with decent performances.</p>
<h2>The naive (slow) solution</h2>
<pre class="brush:fsharp">#light

let triangles =
    Seq.unfold (fun (acc, state) -&gt; Some (acc, (state + acc, state + 1))) (0, 1)
    |&gt; Seq.skip 1 // skip the initial 0

let divides y x =
    x % y = 0

let rec all_factors_slow_rec n i acc =
    match i with
        | 1 -&gt; 1::acc
        | x when divides x n -&gt; all_factors_slow_rec n (x-1) (x::acc)
        | _ -&gt; all_factors_slow_rec n (i-1) acc

let all_factors_slow n =
    all_factors_slow_rec n n []

let find_index m =
    triangles
    |&gt; Seq.map all_factors_slow
    |&gt; Seq.tryFindIndex (fun x -&gt; List.length x &gt;= m)

let resolve_problem_12 =
    let i = find_index 500
    match i with
        | None -&gt; failwith &quot;Cannot resolve problem&quot;
        | Some(i) -&gt;
            let list = triangles |&gt; Seq.take (i+1) |&gt; List.ofSeq
            list.[i]
</pre>
<ul>
<li>Considering that triangle numbers are a mathematical sequence defined as follows: <br />
		<img src="http://l.wordpress.com/latex.php?latex=t_n%20%3D%20t_%7Bn-1%7D%20%2B%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="t_n = t_{n-1} + n" style="vertical-align:-20%;" class="tex" alt="t_n = t_{n-1} + n" /> where <img src="http://l.wordpress.com/latex.php?latex=t_0%20%3D%200&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="t_0 = 0" style="vertical-align:-20%;" class="tex" alt="t_0 = 0" />, then we easily define an F# sequence that yields triangle numbers using <code>Seq.unfold.</code></li>
<li>We then define a function <code>all_factors_slow_rec</code> to calculate all factors (not just primes) of a given number. The slow solution presented in the first listing starts from a number <em>n</em> and then by brute force tries all the numbers down to 1 as a candidate factor.</li>
<li>Once we have these two pieces together, it&#39;s just a matter of enumerating all possible triangle numbers, finding for each their factors (using <code>Seq.map</code>) and finally determining the first triangle number having at least 500 factors (using <code>Seq.tryFindIndex</code>). If <img src="http://l.wordpress.com/latex.php?latex=i&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="i" style="vertical-align:-20%;" class="tex" alt="i" /> is the index of such a number, we then go back to the original sequence of triangles to extract the <img src="http://l.wordpress.com/latex.php?latex=i%5E%7Bth%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="i^{th}" style="vertical-align:-20%;" class="tex" alt="i^{th}" /> element.</li>
</ul>
<h2>An improved version</h2>
<pre class="brush:fsharp">#light

let divides y x =
    x % y = 0

let triangles =
    Seq.unfold (fun (acc, state) -&gt; Some (acc, (state + acc, state + 1))) (0, 1)
    |&gt; Seq.skip 1 // skip the initial 0

let rec all_factors_quick_rec n i factors =
    if divides i n then
        let y = n / i
        if (i &lt; y) then
            all_factors_quick_rec n (i + 1) (i::y::factors)
        elif (i = y) then
            // we have reached the square root value
            i::factors
        else
            factors
    elif i &gt; int (sqrt (float n)) then
        // we are beyond the square root value
        factors
    else
        // try with the next number
        all_factors_quick_rec n (i + 1) factors

let all_factors_quick n =
    all_factors_quick_rec n 1 []

let find_index m =
    triangles
    |&gt; Seq.map all_factors_quick
    |&gt; Seq.tryFindIndex (fun x -&gt; List.length x &gt;= m)

let resolve_problem_12 =
    let i = find_index 500
        match i with
        | None -&gt; failwith &quot;Cannot resolve problem&quot;
        | Some(i) -&gt;
            let list = triangles |&gt; Seq.take (i+1) |&gt; List.ofSeq
            list.[i]
</pre>
<p>The bottleneck of the previous solution is the naive approach to find all the factors of a number. On my machines this solution takes several minutes.</p>
<p>Better performances can be obtained observing that in order to determine all the factors of a number we don&#39;t have try <em>all</em> smaller numbers. As a matter of fact, the following is true (considering <em>n</em> the number to be factorized):</p>
<ul>
<li>if <img src="http://l.wordpress.com/latex.php?latex=n%20%2F%20x%20%3D%20y&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="n / x = y" style="vertical-align:-20%;" class="tex" alt="n / x = y" />, obviously both <em>x</em> and <em>y</em> are factors, so I don&#39;t have to probe <em>y</em> anymore</li>
<li>If I start probing from 2 going up, I can stop probing when I have reached <img src="http://l.wordpress.com/latex.php?latex=%5Csqrt%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\sqrt n" style="vertical-align:-20%;" class="tex" alt="\sqrt n" />. In fact, any number bigger than <img src="http://l.wordpress.com/latex.php?latex=%5Csqrt%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\sqrt n" style="vertical-align:-20%;" class="tex" alt="\sqrt n" /> must have been already found probing a smaller number.</li>
</ul>
<p>Suppose for example that we have to factor the number 36 (one of the triangle numbers):</p>
<ul>
<li>1 is always a factor -&gt; factors = {<strong>1</strong>, <strong>36</strong>}</li>
<li>2 * 18 = 36 -&gt; factors = {1, 36, <strong>2</strong>, <strong>18</strong>}</li>
<li>3 * 12 = 36 -&gt; factors = {1, 36, 2, 18, <strong>3</strong>, <strong>12</strong> }</li>
<li>4 * 9 = 36 -&gt; factors = {1, 36, 2, 18, 3, 12, <strong>4</strong>, <strong>9</strong>}</li>
<li>5 does not divide -&gt; factors = {1, 36, 2, 18, 3, 12, 4, 9}</li>
<li>6 * 6 = 36 -&gt; factors = {1, 36, 2, 18, 3, 12, 4, 9, <strong>6</strong>}</li>
</ul>
<p>We can stop here because if 7 divided 36 evenly, we would have already found a number <em>x</em> &lt; 6 such that 7 * <em>x</em> = 36.</p>
<p>The improved version runs on my machine in less than 1 second.</p>
<p><em><a href="../../tag/euler-problems/" class="broken_link">See all Project Euler problems solutions</a>. </em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-12-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F" style="border: 0px none;" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A RPN Calculator in F#</title>
		<link>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 09:22:36 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[programming praxis]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1164</guid>
		<description><![CDATA[While continuing my journey in F#, after playing with Project Eulero problems for a few weeks, I have come across another excellent&#160; excercise site which goes under the name of Programming Praxis. The first exercise requires to implement a simple calculator using Reverse Polish Notation (RPN). Here follows a simple solution to the problem. Operands [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F01%2Fa-rpn-calculator-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F01%2Fa-rpn-calculator-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>While continuing my journey in F#, after playing with Project Eulero problems for a few weeks, I have come across another excellent&nbsp; excercise site which goes under the name of <a href="http://programmingpraxis.com/" target="_blank">Programming Praxis</a>.</p>
<p>The first exercise requires to implement a simple calculator using <a href="http://en.wikipedia.org/wiki/Reverse_Polish_notation" target="_blank">Reverse Polish Notation (RPN)</a>.</p>
<p>Here follows a simple solution to the problem. Operands are pushed onto the stack until an operator is found: at that point the last two operands are popped from the stack, the operator is applied to them and the result is pushed back on the stack.</p>
<pre class="brush:fsharp">#light

let is_operator c =
    match c with
        | &quot;+&quot; | &quot;-&quot; | &quot;*&quot; | &quot;/&quot;  -&gt; true
        | _ -&gt; false

let calculate left operator right =
    match operator with
        | &quot;+&quot; -&gt; left + right
        | &quot;-&quot; -&gt; left - right
        | &quot;*&quot; -&gt; left * right
        | &quot;/&quot; -&gt; left / right
        | _ -&gt; failwith &quot;Unknown operator&quot;

let proc (item:string) (stack:System.Collections.Generic.Stack&amp;lt;double&gt;) =
    if is_operator item then
        let r = stack.Pop()
        let l = stack.Pop()
        let result = calculate l item r
        stack.Push result
    else
        stack.Push(System.Convert.ToDouble(item))

let evaluate (expression:string) =
    let stack = new System.Collections.Generic.Stack&amp;lt;double&gt;()
    let items = expression.Split([|&#39; &#39; |])
    Array.iter (fun i -&gt; proc i stack) items
    stack.Pop()
</pre>
<ul>
<li>We first define a simple function to check whether a given string is to be interpreted as an arithmetic operand. As you can see, we only support basic operators, nothing too fancy.</li>
<li>We then define a function which takes a double, a string (representing an operator) and another double, and returns the result of applying the given operator to the two numbers.</li>
<li>The <code>proc</code> function takes a string, which represent either an operand or an operator, and a stack of operands. <br />
		If the item contained in the string is an operator, two operands are popped from the stack: the first pop is for the right side operand and the second pop is for the left operand; hence, the operator is applied to the two operands and the result is pushed back onto the stack.<br />
		Otherwise, if it&#39;s an operand, it&#39;s first converted from the string format and pushed onto the stack.</li>
<li>Finally, the entrance point to the program is defined with the <code>evaluate</code> function, which 
<ul>
<li>accepts a string containing the overall expression (such as &quot;1 2 + 4 / 5 * 6 -&quot;)</li>
<li>splits the string into an array of token strings</li>
<li>feed each token into the <code>proc</code> function</li>
<li>finally pops the stack with the last operand to yield the result of the operation.</li>
</ul>
</li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a>
<p><a href="http://dotnetshoutout.com/A-RPN-Calculator-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F01%2Fa-rpn-calculator-in-f%2F" style="border: 0px none;" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 11 in F#</title>
		<link>http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 14:03:25 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1139</guid>
		<description><![CDATA[Project Euler Problem 11 is an interesting one; when addressed with a functional approach it lends itself to be solved using function composition. Let&#39;s have a look at the question and then a possible solution: In the 20&#215;20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F21%2Fproject-euler-problem-11-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F21%2Fproject-euler-problem-11-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=11">Project Euler Problem 11</a> is an interesting one; when addressed with a functional approach it lends itself to be solved using <i><a href="http://en.wikipedia.org/wiki/Function_composition_%28computer_science%29">function composition</a></i>. Let&#39;s have a look at the question and then a possible solution:</p>
<blockquote><p>In the 20&times;20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 <span style="color: red;">26</span> 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 <span style="color: red;">63 </span>94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 <span style="color: red;">78</span> 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 <span style="color: red;">14</span> 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 The product of these numbers is 26 &times; 63 &times; 78 &times; 14 = 1788696. What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 20&times;20 grid?</p></blockquote>
<pre class="brush:fsharp">#light

let numbers =
    array2D [|
      [|08;02;22;97;38;15;00;40;00;75;04;05;07;78;52;12;50;77;91;08|];
      [|49;49;99;40;17;81;18;57;60;87;17;40;98;43;69;48;04;56;62;00|];
      [|81;49;31;73;55;79;14;29;93;71;40;67;53;88;30;03;49;13;36;65|];
      [|52;70;95;23;04;60;11;42;69;24;68;56;01;32;56;71;37;02;36;91|];
      [|22;31;16;71;51;67;63;89;41;92;36;54;22;40;40;28;66;33;13;80|];
      [|24;47;32;60;99;03;45;02;44;75;33;53;78;36;84;20;35;17;12;50|];
      [|32;98;81;28;64;23;67;10;26;38;40;67;59;54;70;66;18;38;64;70|];
      [|67;26;20;68;02;62;12;20;95;63;94;39;63;08;40;91;66;49;94;21|];
      [|24;55;58;05;66;73;99;26;97;17;78;78;96;83;14;88;34;89;63;72|];
      [|21;36;23;09;75;00;76;44;20;45;35;14;00;61;33;97;34;31;33;95|];
      [|78;17;53;28;22;75;31;67;15;94;03;80;04;62;16;14;09;53;56;92|];
      [|16;39;05;42;96;35;31;47;55;58;88;24;00;17;54;24;36;29;85;57|];
      [|86;56;00;48;35;71;89;07;05;44;44;37;44;60;21;58;51;54;17;58|];
      [|19;80;81;68;05;94;47;69;28;73;92;13;86;52;17;77;04;89;55;40|];
      [|04;52;08;83;97;35;99;16;07;97;57;32;16;26;26;79;33;27;98;66|];
      [|88;36;68;87;57;62;20;72;03;46;33;67;46;55;12;32;63;93;53;69|];
      [|04;42;16;73;38;25;39;11;24;94;72;18;08;46;29;32;40;62;76;36|];
      [|20;69;36;41;72;30;23;88;34;62;99;69;82;67;59;85;74;04;36;16|];
      [|20;73;35;29;78;31;90;01;74;31;49;71;48;86;81;16;23;57;05;54|];
      [|01;70;54;71;83;51;54;69;16;92;33;48;61;43;52;01;89;19;67;48|];
      |]

let dimensions = (Array2D.length1 numbers, Array2D.length2 numbers)

let horizontal_traverser (i, j) (iMax, jMax) f_4 =
    if (i &gt; iMax) || (j + 4&gt; jMax) then 0
    else f_4 numbers.[i,j]  numbers.[i, j+1] numbers.[i,j+2] numbers.[i,j+3]

let vertical_traverser (i,j) (iMax, jMax) f_4 =
    if (i + 4 &gt; iMax) || (j &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i+1, j] numbers.[i+2, j] numbers.[i+3,j]

let diagonal_traverser_left_right (i, j) (iMax, jMax) f_4 =
    if (i + 4 &gt; iMax) || (j + 4 &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i+1, j+1] numbers.[i+2, j+2] numbers.[i+3,j+3]

let diagonal_traverser_right_left (i, j) (iMax, jMax) f_4 =
    if (i - 3 &lt; 0) || (j + 4 &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i-1, j+1] numbers.[i-2, j+2] numbers.[i-3,j+3]

let max_in_direction traverser f_4 =
    seq { for i in 0..fst dimensions - 1 do
              for j in 0..snd dimensions - 1 do
                  yield traverser (i,j) dimensions f_4 }
    |&gt; Seq.max

let maximum f_4 =
    [| max_in_direction horizontal_traverser f_4;
       max_in_direction vertical_traverser f_4;
       max_in_direction diagonal_traverser_left_right f_4;
       max_in_direction diagonal_traverser_right_left f_4 |]
    |&gt; Array.max

let problem_11 () =
    maximum (fun a b c d -&gt; a * b * c * d)
</pre>
<ul>
<li>We first declare a two-dimensions array containing the 20&#215;20 numbers that we need to explore. To do this we use F# <a href="http://msdn.microsoft.com/en-us/library/ee353794.aspx">Array2D Module</a>. The same module is used also to compute a tuple containing the size of the two dimension arrays, which we&#39;ll use later on.</li>
<li>We then proceed to define four <i>traverser</i> functions, one for each of these directions: horizontal, vertical, diagonal top-left to bottom-right and diagonal bottom-left to top-right. Each traverser takes as input a given item of the array and applies the supplied 4-parameters function to the starting item plus the next 3 items in a direction. Note how at this point we are not talking about a specific operation (product or sum) yet and we are concentrating on 4 items of the array at a time.</li>
<li>Next we define the <code>max_in_direction</code> function that takes a traverser and a 4-parameters function and finds the maximum value in that particular direction (whatever it might be applying the given function).</li>
<li>We are getting closer to the solution by defining the <code>maximum</code> one-dimension array, where each item is the maximum value in each of the four directions and then taking the highest one.</li>
<li>We finally solve the problem by invoking the <code>maximum</code> function passing to it the product of four items as a lambda.</li>
</ul>
<p>Note how easy it is to change the particular function that we use to aggregate the 4 items: suppose for example that we are interested in the 4 items giving the maximum <i>sum</i>, we could simply invoke:</p>
<pre class="brush:csharp">maximum (fun a b c d -&gt; a + b + c + d)
</pre>
<p>
<a href="../../tag/euler-problems/" class="broken_link">See all Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-11-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F21%2Fproject-euler-problem-11-in-f%2F" style="border: 0px none;" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 10 in F#</title>
		<link>http://stefanoricciardi.com/2010/09/14/project-euler-problem-10-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/09/14/project-euler-problem-10-in-f/#comments</comments>
		<pubDate>Tue, 14 Sep 2010 15:05:01 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1124</guid>
		<description><![CDATA[Project Euler Problem 10 asks a very simple question, again dealing with prime numbers: Calculate the sum of all the primes below two million. I am giving here two solutions, using two different approaches: #light open System.Collections.Generic // SOLUTION 1: TRIAL DIVISION let is_prime (x:int64) = let rec check i = double i &#62; sqrt [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F14%2Fproject-euler-problem-10-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F14%2Fproject-euler-problem-10-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=10">Project Euler Problem 10</a> asks a very simple question, again dealing with prime numbers:</p>
<blockquote><p>
Calculate the sum of all the primes below two million.
</p></blockquote>
<p>I am giving here two solutions, using two different approaches:</p>
<pre class="brush:csharp">
#light

open System.Collections.Generic

// SOLUTION 1: TRIAL DIVISION
let is_prime (x:int64) =
    let rec check i =
        double i &gt; sqrt (double x) || (x % i &lt;&gt; 0L &amp;&amp; check (i + 1L))
    check 2L  

let trial_division (n:int64) =
    seq { for i in 2L .. n do
          if is_prime i then yield i }
    |&gt; Seq.takeWhile (fun x -&gt; x &lt; n)
    |&gt; Seq.sum

// SOLUTION 2: USE THE SIEVE
let sieve (n:int64) =
    let candidatePrimes = new Dictionary&lt;int64, bool&gt;()
    for i in 2L .. n do candidatePrimes.Add(i, true)
    for i in 2L .. n/2L do
        if candidatePrimes.[i] = true then
            let mutable j = i
            while (j + i <= n) do
                j &lt;- j + i
                candidatePrimes.[j] <- false
    seq { for i in 2L .. n do
            if candidatePrimes.[i] = true then
                yield i }
    |&gt; Seq.sum
</pre>
<ul>
<li> The first solution uses <a href="http://en.wikipedia.org/wiki/Trial_division">trial division</a> to create a sequence of all primes under a certain threshold. It's the easiest method to understand.</li>
<li> The second solution is a naive implementation of the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Erathostenes</a>.  I first mark all the numbers as candidate primes; then starting from 2 I mark off all the multiples, move to the next candidate prime, until only primes are left (you can refer to the Wikipedia article for all the details).
<p> As you can see, this second solution looks has a more imperative feel to it, using mutable data (a dictionary and a counter). Based on my tests for numbers from 1 to 10 millions, it's at least twice as fast as the trial division method.
</li>
</ul>
<p><a href="../../tag/euler-problems/" class="broken_link">See all  Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/09/14/project-euler-problem-10-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/09/14/project-euler-problem-10-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-10-in-F-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F14%2Fproject-euler-problem-10-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/09/14/project-euler-problem-10-in-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 9 in F#</title>
		<link>http://stefanoricciardi.com/2010/08/25/project-euler-problem-9-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/08/25/project-euler-problem-9-in-f/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 15:33:02 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1079</guid>
		<description><![CDATA[Project Euler Problem 9 introduces the interesting mathematical concept of Pythagorean Triple. Let&#8217;s have a look at the question: A Pythagorean triplet is a set of three natural numbers, a &#60; b &#60; c, for which, a&#178; + b&#178; = c&#178; For example, 3&#178; + 4&#178; = 9 + 16 = 25 = 5&#178;. There [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F25%2Fproject-euler-problem-9-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F25%2Fproject-euler-problem-9-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=9">Project Euler Problem 9</a> introduces the interesting mathematical concept of <a href="http://en.wikipedia.org/wiki/Pythagorean_triple">Pythagorean Triple</a>.  Let&#8217;s have a look at the question:</p>
<blockquote><p>
A Pythagorean triplet is a set of three natural numbers, a &lt; b &lt; c, for which,<br />
a&sup2; + b&sup2; = c&sup2;</p>
<p>For example, 3&sup2; + 4&sup2; = 9 + 16 = 25 = 5&sup2;.</p>
<p>There exists exactly one Pythagorean triplet for which a + b + c = 1000.<br />
Find the product abc.
</p></blockquote>
<p>As usual, I first show my solution and then comment on the approach:</p>
<pre class="brush:fsharp">
#light

// generate triplets using Euclid's Formula
let pythagorean_triplets top =
    [ for m in 1 .. top do
          for n in 1 .. m-1 do
          let a = m*m-n*n
          let b = 2*m*n
          let c = m*m+n*n
          yield [a;b;c] ]

// multiply all the values of a list
let multiply_list list =
    List.fold (fun acc elem -&gt; acc*elem) 1 list

// find a triplet where the sum of values
// is equal to a given number
let find_triplet_with_sum sum =
    pythagorean_triplets sum
    |&gt; List.find (fun [a;b;c] -&gt; a+b+c=sum)

let problem_9 () =
    find_triplet_with_sum 1000
    |&gt; multiply_list
</pre>
<p>Let&#8217;s go through the solution step by step:</p>
<ul>
<li>The first function, <code>pythagorean_triplets</code> uses <a href="http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple">Euclid&#8217;s Formula</a> to enumerate all possible Pytagorean Triplets up to a given threshold. The formula can be summarized like this:<br />
<cite>a = m&sup2; &#8211; n&sup2;, b = 2mn, c = m&sup2; + n&sup2;,  where m and n are positive integers with m &gt; n.</cite></p>
<p>It&#8217;s interesting to note that each item of the list is itself a <em>list</em> of three numbers. I could have generated a tuple, but since in the end I need to multiply all the 3 values together, the list was more straightfoward to use.
</li>
<li><code>multiply_list</code> is just a convenience function to multiply all the elements of a list together</li>
<li><code>find_triplet_with_sum</code> does the heavy work of generating the actual triplets picking the first one where the sum is equal to a given value.</li>
<li> At the end I just put the pieces together and solve the problem. </li>
</ul>
<p>One caveat: Euclid&#8217;s Formula does not generate <em>all</em> Pytagorean Triplets(there are other formulas that do). I can say that I have been lucky that it generated the one requested by the Project&#8217;s Euler problem. The code above might not work if the goal is changed to find a triplet with a different product.</p>
<p><a href="../../tag/euler-problems/" class="broken_link">See all  Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/08/25/project-euler-problem-9-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/08/25/project-euler-problem-9-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-9-in-F-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F25%2Fproject-euler-problem-9-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/08/25/project-euler-problem-9-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 8 in F#</title>
		<link>http://stefanoricciardi.com/2010/08/17/project-euler-problem-8-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/08/17/project-euler-problem-8-in-f/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 21:04:43 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1044</guid>
		<description><![CDATA[After two easy problems, it&#8217;s now time for Problem 8. At first, this problem also seemed to me more complex than it really is. Let&#8217;s have a look at the question: 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 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F17%2Fproject-euler-problem-8-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F17%2Fproject-euler-problem-8-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>After <a href="http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/">two easy problems</a>, it&#8217;s now time for Problem 8. </p>
<p>At first, this problem also seemed to me more complex than it really is.  Let&#8217;s have a look at the question:</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>So, basically what we need to do is: </p>
<ul>
<li>consider all chunks of this list of numbers that can be created by taking 5 consecutive digits from the beginning till the end (there will be <em>n-5</em> chunks if <em>n</em> is the number of digits in the list)</li>
<li>for each chunk, multiply all the digits together (that&#8217;s <em>n-1</em> products per chunk)</li>
<li>pick the value corresponding to the greatest product.</li>
</ul>
<p>At first I have considered resolving an easier problem first, like: find the chunk whose <em>sum</em> is bigger and then calculate that product. Assuming that sum is cheaper to calculate than product (and it is), we would have had <em>(n-5) * (n-1)</em> sums and just 1 product. However you can easily find examples where the sum of the digits is the same while the product is different: e.g. <em>4 + 5 = 7 + 2 = 9</em> but <em>4 * 5 = 20 > 7 * 2 = 14</em>. Therefore that was a dead end.</p>
<p>A more mathematically sound approach to find the chunk giving the highest product might have been to first locate the chunk with the highest sum of <em>logarithms</em> of each digit and then calculate the corresponding product. However, a quick test revealed that logarithm is <em>way</em> slower than product.</p>
<p>Finally, a couple of micro-optimizations that occurred to me.</p>
<ul>
<li>You can skip all chunks containing at least one 0 (trivially, the product will be zero)</li>
<li>You don&#8217;t really have to multiply all the digits for each chunk (that is <em>(n-5) * (n-1)</em> products): once you have computed the product of the first chunk, the product of the next chunk would be the product of the previous chunk <em>times</em> the sixth digit <em>divided</em> by the first digit, and so on for subsequent chunks.
</ul>
<p>Eventually, I did not try to implement these two things, since brute force, which I am about to show you, is so quick that it&#8217;s wasn&#8217;t really worth it:</p>
<pre class="brush:fsharp">
#light

let digits = [| 7; 3; 1; 6; 7; 1; 7; 6; 5; 3; 1; 3; 3; 0; 6; 2; 4; 9;
    1; 9; 2; 2; 5; 1; 1; 9; 6; 7; 4; 4; 2; 6; 5; 7; 4; 7; 4; 2; 3; 5;
    5; 3; 4; 9; 1; 9; 4; 9; 3; 4; 9; 6; 9; 8; 3; 5; 2; 0; 3; 1; 2; 7;
    7; 4; 5; 0; 6; 3; 2; 6; 2; 3; 9; 5; 7; 8; 3; 1; 8; 0; 1; 6; 9; 8;
    4; 8; 0; 1; 8; 6; 9; 4; 7; 8; 8; 5; 1; 8; 4; 3; 8; 5; 8; 6; 1; 5;
    6; 0; 7; 8; 9; 1; 1; 2; 9; 4; 9; 4; 9; 5; 4; 5; 9; 5; 0; 1; 7; 3;
    7; 9; 5; 8; 3; 3; 1; 9; 5; 2; 8; 5; 3; 2; 0; 8; 8; 0; 5; 5; 1; 1;
    1; 2; 5; 4; 0; 6; 9; 8; 7; 4; 7; 1; 5; 8; 5; 2; 3; 8; 6; 3; 0; 5;
    0; 7; 1; 5; 6; 9; 3; 2; 9; 0; 9; 6; 3; 2; 9; 5; 2; 2; 7; 4; 4; 3;
    0; 4; 3; 5; 5; 7; 6; 6; 8; 9; 6; 6; 4; 8; 9; 5; 0; 4; 4; 5; 2; 4;
    4; 5; 2; 3; 1; 6; 1; 7; 3; 1; 8; 5; 6; 4; 0; 3; 0; 9; 8; 7; 1; 1;
    1; 2; 1; 7; 2; 2; 3; 8; 3; 1; 1; 3; 6; 2; 2; 2; 9; 8; 9; 3; 4; 2;
    3; 3; 8; 0; 3; 0; 8; 1; 3; 5; 3; 3; 6; 2; 7; 6; 6; 1; 4; 2; 8; 2;
    8; 0; 6; 4; 4; 4; 4; 8; 6; 6; 4; 5; 2; 3; 8; 7; 4; 9; 3; 0; 3; 5;
    8; 9; 0; 7; 2; 9; 6; 2; 9; 0; 4; 9; 1; 5; 6; 0; 4; 4; 0; 7; 7; 2;
    3; 9; 0; 7; 1; 3; 8; 1; 0; 5; 1; 5; 8; 5; 9; 3; 0; 7; 9; 6; 0; 8;
    6; 6; 7; 0; 1; 7; 2; 4; 2; 7; 1; 2; 1; 8; 8; 3; 9; 9; 8; 7; 9; 7;
    9; 0; 8; 7; 9; 2; 2; 7; 4; 9; 2; 1; 9; 0; 1; 6; 9; 9; 7; 2; 0; 8;
    8; 8; 0; 9; 3; 7; 7; 6; 6; 5; 7; 2; 7; 3; 3; 3; 0; 0; 1; 0; 5; 3;
    3; 6; 7; 8; 8; 1; 2; 2; 0; 2; 3; 5; 4; 2; 1; 8; 0; 9; 7; 5; 1; 2;
    5; 4; 5; 4; 0; 5; 9; 4; 7; 5; 2; 2; 4; 3; 5; 2; 5; 8; 4; 9; 0; 7;
    7; 1; 1; 6; 7; 0; 5; 5; 6; 0; 1; 3; 6; 0; 4; 8; 3; 9; 5; 8; 6; 4;
    4; 6; 7; 0; 6; 3; 2; 4; 4; 1; 5; 7; 2; 2; 1; 5; 5; 3; 9; 7; 5; 3;
    6; 9; 7; 8; 1; 7; 9; 7; 7; 8; 4; 6; 1; 7; 4; 0; 6; 4; 9; 5; 5; 1;
    4; 9; 2; 9; 0; 8; 6; 2; 5; 6; 9; 3; 2; 1; 9; 7; 8; 4; 6; 8; 6; 2;
    2; 4; 8; 2; 8; 3; 9; 7; 2; 2; 4; 1; 3; 7; 5; 6; 5; 7; 0; 5; 6; 0;
    5; 7; 4; 9; 0; 2; 6; 1; 4; 0; 7; 9; 7; 2; 9; 6; 8; 6; 5; 2; 4; 1;
    4; 5; 3; 5; 1; 0; 0; 4; 7; 4; 8; 2; 1; 6; 6; 3; 7; 0; 4; 8; 4; 4;
    0; 3; 1; 9; 9; 8; 9; 0; 0; 0; 8; 8; 9; 5; 2; 4; 3; 4; 5; 0; 6; 5;
    8; 5; 4; 1; 2; 2; 7; 5; 8; 8; 6; 6; 6; 8; 8; 1; 1; 6; 4; 2; 7; 1;
    7; 1; 4; 7; 9; 9; 2; 4; 4; 4; 2; 9; 2; 8; 2; 3; 0; 8; 6; 3; 4; 6;
    5; 6; 7; 4; 8; 1; 3; 9; 1; 9; 1; 2; 3; 1; 6; 2; 8; 2; 4; 5; 8; 6;
    1; 7; 8; 6; 6; 4; 5; 8; 3; 5; 9; 1; 2; 4; 5; 6; 6; 5; 2; 9; 4; 7;
    6; 5; 4; 5; 6; 8; 2; 8; 4; 8; 9; 1; 2; 8; 8; 3; 1; 4; 2; 6; 0; 7;
    6; 9; 0; 0; 4; 2; 2; 4; 2; 1; 9; 0; 2; 2; 6; 7; 1; 0; 5; 5; 6; 2;
    6; 3; 2; 1; 1; 1; 1; 1; 0; 9; 3; 7; 0; 5; 4; 4; 2; 1; 7; 5; 0; 6;
    9; 4; 1; 6; 5; 8; 9; 6; 0; 4; 0; 8; 0; 7; 1; 9; 8; 4; 0; 3; 8; 5;
    0; 9; 6; 2; 4; 5; 5; 4; 4; 4; 3; 6; 2; 9; 8; 1; 2; 3; 0; 9; 8; 7;
    8; 7; 9; 9; 2; 7; 2; 4; 4; 2; 8; 4; 9; 0; 9; 1; 8; 8; 8; 4; 5; 8;
    0; 1; 5; 6; 1; 6; 6; 0; 9; 7; 9; 1; 9; 1; 3; 3; 8; 7; 5; 4; 9; 9;
    2; 0; 0; 5; 2; 4; 0; 6; 3; 6; 8; 9; 9; 1; 2; 5; 6; 0; 7; 1; 7; 6;
    0; 6; 0; 5; 8; 8; 6; 1; 1; 6; 4; 6; 7; 1; 0; 9; 4; 0; 5; 0; 7; 7;
    5; 4; 1; 0; 0; 2; 2; 5; 6; 9; 8; 3; 1; 5; 5; 2; 0; 0; 0; 5; 5; 9;
    3; 5; 7; 2; 9; 7; 2; 5; 7; 1; 6; 3; 6; 2; 6; 9; 5; 6; 1; 8; 8; 2;
    6; 7; 0; 4; 2; 8; 2; 5; 2; 4; 8; 3; 6; 0; 0; 8; 2; 3; 2; 5; 7; 5;
    3; 0; 4; 2; 0; 7; 5; 2; 9; 6; 3; 4; 5; 0|]

let calculate_max_chunk_product chunk_size =
    seq {
        for i in 0 .. (Array.length digits - chunk_size) do
            let chunk = Array.sub digits i chunk_size
            yield Array.fold (fun acc elem -> acc * elem) 1 chunk
        }
    |> Seq.max

let problem_8 () =
    calculate_max_chunk_product 5
</pre>
<p>As you can see, we are generating a sequence of products and then pick the maximum value. Each product is created by first taking a chunk of the array (using the <code>Array.sub</code>) and then using <code>Array.fold</code> to compute the product of all elements in the chunk.</p>
<p>Again, I have tried to keep the imperative part to a minimum and I was able to get by without using any mutable variable.</p>
<p><a href="../../tag/euler-problems/" class="broken_link">See all  Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/08/17/project-euler-problem-8-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/08/17/project-euler-problem-8-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a> </p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-8-in-F-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F17%2Fproject-euler-problem-8-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/08/17/project-euler-problem-8-in-f/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 6 and 7 in F#</title>
		<link>http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 07:03:10 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1018</guid>
		<description><![CDATA[Project Euler problem 6 is one of the easiest that I have encountered so far. Also, Problem 7 is quite easy to solve once you have a function for prime numbers (something we did in Problem 3). Therefore, in this post I give 2 problems for the price of 1! Problem 6 Let&#8217;s have a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F16%2Fproject-euler-problem-6-and-7-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F16%2Fproject-euler-problem-6-and-7-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Project Euler problem 6 is one of the easiest that I have encountered so far. Also, Problem 7 is quite easy to solve once you have a function for prime numbers (something we did in <a href="http://stefanoricciardi.com/2010/07/01/project-euler-problem-3-in-f/">Problem 3</a>). Therefore, in this post I give 2 problems for the price of 1! <img src='http://stefanoricciardi.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Problem 6</h2>
<p>Let&#8217;s have a look at the question for Problem 6:</p>
<blockquote><p>
The sum of the squares of the first ten natural numbers is,</p>
<p>1&sup2; + 2&sup2; + &#8230; + 10&sup2; = 385<br />
The square of the sum of the first ten natural numbers is,</p>
<p>(1 + 2 + &#8230; + 10)&sup2; = 55&sup2; = 3025</p>
<p>Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 &#8211; 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>There are a few tricks to calculate the sum of the squares (see for example <a href="http://">here</a>). However, given the limited size of the problem at hand, brute-force is perfectly fine: it shows once more the elegance of a declarative solution.</p>
<pre class="brush: fsharp">
#light
open System

let square x = x * x

// a&sup2; + b&sup2;  + ... + z&sup2;
let sum_of_square max =
    Seq.unfold (fun x -> if x > max then None else Some(x*x, x+1)) 1
    |> Seq.sum

// (a +b + ... + z)&sup2;
let square_of_sum max =
    {1 .. max}
    |> Seq.sum
    |> square

let problem_6 max =
    square_of_sum(max) - sum_of_square(max)
</pre>
<h2>Problem 7</h2>
<blockquote><p>
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.</p>
<p>What is the 10001st prime number?
</p></blockquote>
<p>As I mentioned in the introduction, this one is fairly easy once you know how to tell whether a given number is prime or not. We did that exercise in <a href="http://stefanoricciardi.com/2010/07/01/project-euler-problem-3-in-f/">Problem 3</a>. </p>
<p>There&#8217;s a catch though: this time we are <i>counting</i> the prime numbers. In the test we did in <a href="http://stefanoricciardi.com/2010/07/01/project-euler-problem-3-in-f/">Problem 3</a> there was a small error that in that context was irrelevant: the test returned <code>true</code> also for 0 and 1, which strictly speaking are not prime numbers (2 is considered to be the first prime number).</p>
<p>For this reason, I have modified the code of <code>is_prime</code> a bit so that the first prime will be 2, the second 3, and so on as appropriate.</p>
<pre class="brush: fsharp">
#light
open System

let is_prime x =
    let rec check i =
        x &gt; 1L &amp;&amp;
       (double i &gt; sqrt (double x) || (x % i &lt;&gt; 0L &#038;&#038; check (i + 1L)))
    check 2L                 

let sequence_of_first_n_primes n =
    Seq.initInfinite (fun x -&gt; int64 x)
    |&gt; Seq.filter is_prime
    |&gt; Seq.take n
    |&gt; Seq.max
</pre>
<p>Ok&#8230; break time is over. <a href="http://projecteuler.net/index.php?section=problems&#038;id=8">Problem 8</a> looks a bit more challenging. See you when I have got a nice solution for that.</p>
<p><a href="../../tag/euler-problems/" class="broken_link">See all  Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-6-and-7-in-F-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F08%2F16%2Fproject-euler-problem-6-and-7-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/08/16/project-euler-problem-6-and-7-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

