<?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>Ståle's weblog &#187; Euler</title>
	<atom:link href="http://blog.staale.org/category/euler/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.staale.org</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Mon, 07 Sep 2009 13:35:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Euler problem 8 solved in Scala and Python</title>
		<link>http://blog.staale.org/2009/08/euler-problem-8-solved-in-scala-and-python.html</link>
		<comments>http://blog.staale.org/2009/08/euler-problem-8-solved-in-scala-and-python.html#comments</comments>
		<pubDate>Wed, 12 Aug 2009 07:10:23 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=128</guid>
		<description><![CDATA[Problem 8 in project Euler is:
Find the greatest product of five consecutive digits in the 1000-digit number.
The first step is just to copy and paste the big block off numbers into a new file. I preserved line breaks and everything in my file, and called it Euler008-data.txt.
Since I day to day program in Python, and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=8">Problem 8</a> in project Euler is:</p>
<blockquote><p>Find the greatest product of five consecutive digits in the 1000-digit number.</p></blockquote>
<p>The first step is just to copy and paste the big block off numbers into a new file. I preserved line breaks and everything in my file, and called it Euler008-data.txt.</p>
<p>Since I day to day program in Python, and have been pretty happy with how Python handles file reading, I wanted to compare the Scala code for this to the equivalent Python code. I first present the Python solution for extracting the number into 1 long string:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="python" style="font-family:monospace;">digit = <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Euler008-data.txt&quot;</span><span style="color: black;">&#41;</span>.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Pretty short one-liner. I first open the file and read the entire content, giving me a single big string with linebreaks. I then use the default split method which splits on whitespace to create an array of strings, one for each line. Then finally that list is joined with nothing between the numbers. The result is one big number of strings.</p>
<p>Next I need a method for calculating the product of the digits in a string, I will use this method on each segment of 5 numbers in the digit string:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> prodDigits<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
    prod = <span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> d <span style="color: #ff7700;font-weight:bold;">in</span> n: prod <span style="color: #66cc66;">*</span>= <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>d<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> prod</pre></td></tr></table></div>

<p>Her it&#8217;s just a matter of iterating over the characters in the string, converting each to an int and multiplying them together.</p>
<p>Finally we need to test each subset of 5 digits. I include here the complete program for finding the solution.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> prodDigits<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
        prod = <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> d <span style="color: #ff7700;font-weight:bold;">in</span> n: prod <span style="color: #66cc66;">*</span>= <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>d<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> prod
    digit = <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Euler008-data.txt&quot;</span><span style="color: black;">&#41;</span>.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    maxval = <span style="color: #ff4500;">0</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> n <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #008000;">len</span><span style="color: black;">&#40;</span>digit<span style="color: black;">&#41;</span>-<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>:
        maxval = <span style="color: #008000;">max</span><span style="color: black;">&#40;</span>maxval, prodDigits<span style="color: black;">&#40;</span>digit<span style="color: black;">&#91;</span>n:n+<span style="color: #ff4500;">5</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> maxval</pre></td></tr></table></div>

<p>Now for the Scala solution. I import and use the scala.io.Source.fromFile method for extracting the data from the file. The fromFile returns a list of characters, for the content off a file. To convert this into one big digit string, I just filter out all the newlines, then turn the list into a string with mkString:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> digit <span style="color: #000080;">=</span> fromFile<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Euler008-data.txt&quot;</span><span style="color: #F78811;">&#41;</span> filter <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_!=</span><span style="color: #6666FF;">'<span style="color: #0000ff; font-weight: bold;">\n</span>'</span><span style="color: #F78811;">&#41;</span> mkString</pre></td></tr></table></div>

<p>Next we need the method for converting a string to the product of its digits. To do that, I map the string from a list of chars to a list of ints, by substracting &#8216;0&#8242; from each value, then I fold that list using the multiply operator:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> prodDigits<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>String<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> /<span style="color: #000080;">:</span> <span style="color: #F78811;">&#40;</span>n map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>-<span style="color: #6666FF;">'0'</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_*_</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>Thanks to Scalas functional nature, this is a much shorter function than the same in Python. I add an extra step in scala, where I convert the digit string into a list of parts, each beeing 1 subset of 5 strings from the digit string:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> parts <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>n <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">0</span> until digit.<span style="color: #000000;">length</span>-<span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> digit.<span style="color: #000000;">substring</span><span style="color: #F78811;">&#40;</span>n,n+<span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>The final step is to map all the parts into products, then find the max value, here is the complete program:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> scala.<span style="color: #000000;">io</span>.<span style="color: #000000;">Source</span>.<span style="color: #000000;">fromFile</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">object</span> Euler008 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> prodDigits<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>String<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> /<span style="color: #000080;">:</span> <span style="color: #F78811;">&#40;</span>n map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>-<span style="color: #6666FF;">'0'</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_*_</span><span style="color: #F78811;">&#41;</span>
&nbsp;
    <span style="color: #0000ff; font-weight: bold;">val</span> digit <span style="color: #000080;">=</span> fromFile<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Euler008-data.txt&quot;</span><span style="color: #F78811;">&#41;</span> filter <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_!=</span><span style="color: #6666FF;">'<span style="color: #0000ff; font-weight: bold;">\n</span>'</span><span style="color: #F78811;">&#41;</span> mkString
    <span style="color: #0000ff; font-weight: bold;">val</span> parts <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>n <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">0</span> until digit.<span style="color: #000000;">length</span>-<span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> digit.<span style="color: #000000;">substring</span><span style="color: #F78811;">&#40;</span>n,n+<span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span>
&nbsp;
    <span style="color: #0000ff; font-weight: bold;">val</span> max <span style="color: #000080;">=</span> parts map prodDigits reduceLeft<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span>a,b<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">&gt;</span>b<span style="color: #F78811;">&#41;</span> a <span style="color: #0000ff; font-weight: bold;">else</span> b<span style="color: #F78811;">&#41;</span>
    println<span style="color: #F78811;">&#40;</span>max<span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>I think Scala is great for simple file handling (there are other methods to turn files into a list of strings as well), and the product method gets pretty small thanks to functional programming. The actual runtime is faster for the Python program though. Partly because of the JavaVM startup overhead, and also because I didn&#8217;t create a list of substrings in Python, which is an extra 995 object creations.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/08/euler-problem-8-solved-in-scala-and-python.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Euler problems solved</title>
		<link>http://blog.staale.org/2009/05/more-euler-problems-solved.html</link>
		<comments>http://blog.staale.org/2009/05/more-euler-problems-solved.html#comments</comments>
		<pubDate>Tue, 05 May 2009 07:12:10 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=107</guid>
		<description><![CDATA[Today I am feeling generous, so I will go through a couple off Euler problems in 1 post. First up is the 6th problem, here is the short version off the problem:
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum
Thanks to the [...]]]></description>
			<content:encoded><![CDATA[<p>Today I am feeling generous, so I will go through a couple off Euler problems in 1 post. First up is the 6th problem, here is the short version off the problem:</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>Thanks to the ease of creating ranges and applying functions to them in Scala, this turns out to be pretty easy:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> sumOfSquares <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">100</span><span style="color: #F78811;">&#41;</span> map <span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">=&gt;</span>a<span style="color: #000080;">*</span>a<span style="color: #F78811;">&#41;</span> reduceLeft <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span>
<span style="color: #0000ff; font-weight: bold;">val</span> squareOfSum <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>BigInt<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> /<span style="color: #000080;">:</span> <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">100</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span> pow<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span>
println squareOfSum - sumOfSquares</pre></td></tr></table></div>

<p>Pretty simple code. The first line just maps each number in the 1 to 100 range to their 2nd power, then sums them all using reduceLeft. The second line uses the fold left operator (/:) to sum all the numbers in the 1 to 100 range into a single BigInt, which we then call the pow(2) method on to get the power off 2. Finally it&#8217;s just subtracting the 2 numbers.</p>
<p>Now onto problem 7:</p>
<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>The best way to find prime numbers, is to use the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of  Eratosthenes</a>. We do this using a bitset. We start at index 2, and for each index we find that is not marked, we mark all the multiples for that index. So we first look at index 2, this is not marked, so we mark 4,6,8,10 and so on, up to our max. We then check index 3, this is not marked, so we mark 6,9,12,15 and so on. Then we go to index 4, this is marked, so we don&#8217;t do anything. This goes on until half the max value. Now we have a bit set where all non-primes are marked. Here is the method implemented in Scala using a mutable BitSet:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> scala.<span style="color: #000000;">collection</span>.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">def</span> primesUpTo<span style="color: #F78811;">&#40;</span>max<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">val</span> nonPrimes <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> mutable.<span style="color: #000000;">BitSet</span>
    <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>n <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">2</span> to <span style="color: #F78811;">&#40;</span>max/<span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #000080;">!</span>nonPrimes<span style="color: #F78811;">&#40;</span>n<span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span> x <span style="color: #000080;">&lt;</span>- n<span style="color: #000080;">*</span><span style="color: #F78811;">2</span> until<span style="color: #F78811;">&#40;</span>max,n<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
        nonPrimes +<span style="color: #000080;">=</span> x
    <span style="color: #F78811;">&#125;</span>
    <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>n <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">1</span> to max<span style="color: #000080;">;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #000080;">!</span>nonPrimes<span style="color: #F78811;">&#40;</span>n<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> n
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>We first import everything in the scala.collections package, then mutable.BitSet can be resolved to scala.collections.mutable.BitSet. This is an extension to the package system in Java where only classes can be imported, in Scala we can import namespaces and refer to things within those namespaces. Now we iterate from 2 until max/2, for each number we see if it&#8217;s not set in the bitset, if it isn&#8217;t we iterate until max with a step off n, and mark off each multiple. Finally we just iterate over the entire bitset, and yield all unmarked values, as those will be the primes.</p>
<p>Now to get the solution to the problem, we just need to figure out a max value that creates more than 10001 primes, and get the 10001th prime from that:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;">println<span style="color: #F78811;">&#40;</span>primesUpTo<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">500000</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">10001</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>Now I am going to skip number 8, as I can use that to deal with file parsing, and instead move directly on to number 9:</p>
<blockquote><p>A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,<br />
a² + b² = c²</p>
<p>For example, 3² + 4² = 9 + 16 = 25 = 5².</p>
<p>There exists exactly one Pythagorean triplet for which a + b + c = 1000.<br />
Find the product abc.
</p></blockquote>
<p>There are some clever ways off doing this, but I am just heading straight for brute force solution to this one, as the solution space is pretty small.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> n <span style="color: #000080;">=</span> <span style="color: #F78811;">1000</span>
<span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>a <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">1</span> to n<span style="color: #000080;">;</span> b <span style="color: #000080;">&lt;</span>- a to n-a<span style="color: #000080;">;</span> c<span style="color: #000080;">=</span>n-a-b<span style="color: #000080;">;</span>if a<span style="color: #000080;">*</span>a+b<span style="color: #000080;">*</span>b<span style="color: #000080;">==</span>c<span style="color: #000080;">*</span>c<span style="color: #F78811;">&#41;</span> println<span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">*</span>b<span style="color: #000080;">*</span>c<span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>Since I use the target value 1000 a few times, I just put it in a constant that I can refer to. I first iterate a from 1 to 1000, then b goes from a to n-a, and c will then have to be 1000-a-b for the a and b that are set at that part in the iteration. We then just check if the values we have for a,b and c fulfill the Pythagorean formula, and print the product off the first one we find. Short and sweet.</p>
<p>That&#8217;s it for todays program. Next up will problem 8, and file parsing, which I haven&#8217;t looked into yet for Scala. I will have to compare it to Python, which has some nice and simple features for text file parsing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/05/more-euler-problems-solved.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler problem 5 in Scala</title>
		<link>http://blog.staale.org/2009/04/euler-problem-5-in-scala.html</link>
		<comments>http://blog.staale.org/2009/04/euler-problem-5-in-scala.html#comments</comments>
		<pubDate>Wed, 22 Apr 2009 19:20:45 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=90</guid>
		<description><![CDATA[Long time since last update now. I have been out traveling in Americaland again, but I am now back. Not that there are many reading this blog, but I at least try and keep myself busy working through these Euler problems to practice my Scala.
Problem 5 in project euler deals with finding the smallest number [...]]]></description>
			<content:encoded><![CDATA[<p>Long time since last update now. I have been out traveling in Americaland again, but I am now back. Not that there are many reading this blog, but I at least try and keep myself busy working through these Euler problems to practice my Scala.</p>
<p>Problem 5 in project euler deals with finding the smallest number that divides with a range off numbers:</p>
<blockquote>
<div class="problem_content">
<p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p>
<p>What is the smallest number that is <dfn title="divisible with no remainder">evenly divisible</dfn> by all of the numbers from 1 to 20?</div>
</blockquote>
<p>This is actually pretty easy to just solve directly. We start with just multiplying all the numbers from 1 to 20:</p>
<p>1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20</p>
<p>If you examine this, 20 is 10*2, and we allready have that in our set, so we can drop it. 18 is 2*9, so we can drop that as well. 16 is 2*2*2*2, 8 is 2*2*2, 4 is 2*2 and 2 is just 2. Since 16 covers all those divisors, we can drop 2,4 and 8. With that, we are reduced to:</p>
<p>1 * 3 * 5 * 6 * 7 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 19</p>
<p>Still, we can remove more numbers. 15 is 3*5, 14 is 2*7, 12 is 2*6, and 10 is 2*5, leaving us with:</p>
<p>1 * 3 * 5 * 6 * 7 * 9 * 10 * 11 * 13 * 16 * 17 * 19</p>
<p>2 and 3 are factors of 16 and 9 respectivly, which means we can remove both 3 and 6. 10 is 5*2, we have 5 and 2 as a factor off 16. This finally leaves us with:</p>
<p>5*7*9*11*13*16*17*19</p>
<p>Which proves to be the right answer. So this can be pretty easily solved just using conventional math.</p>
<p>Now for a Scala solution. What I intend to do here is to create a list of 1 to 20. For each value at index n in the list, I divide the value at n+1 -&gt; max by n if it&#8217;s divisible by n. For the first number, 1, nothing changes. But applying the same to the list using 2, results in the following updated list:</p>
<p>1,2,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10</p>
<p>Every even number after 2 gets divided by 2. This produces a new list, and we repeat this process for the next number, 3:</p>
<p>1,2,3,2,5,1,7,4,3,5,11,2,13,7,5,8,17,3,19,10</p>
<p>Since 6 was divisible by both, it&#8217;s now reduced to 1. If we keep repeating this process, we will end up with a list of unique factors in the final answer. Now for the code applying this to a list.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> reduceMuls<span style="color: #F78811;">&#40;</span>src<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    src.<span style="color: #000000;">head</span> <span style="color: #000080;">::</span> reduceMuls<span style="color: #F78811;">&#40;</span>src.<span style="color: #000000;">head</span>, src.<span style="color: #000000;">tail</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">def</span> reduceMuls<span style="color: #F78811;">&#40;</span>div<span style="color: #000080;">:</span>Int, target<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>target.<span style="color: #000000;">tail</span>.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">return</span> target
    <span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> target map<span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">=&gt;</span>if<span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">%</span>div<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> a/div <span style="color: #0000ff; font-weight: bold;">else</span> a<span style="color: #F78811;">&#41;</span>
    res.<span style="color: #000000;">head</span> <span style="color: #000080;">::</span> reduceMuls<span style="color: #F78811;">&#40;</span>res.<span style="color: #000000;">head</span>, res.<span style="color: #000000;">tail</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>Ok, the first function here is just a simple wrapper that extracts the first and reminder off the list, and passes it on to the second method. Line 5 is just a check for empty lists. Line 6 does the magic, it maps the target list by dividing all numbers in it if it&#8217;s divisible by div, the first argument. This new list is then modified by applying the same function to all but it&#8217;s first element, and adding the first element to the start. The argument at each stage off the process looks as follows:</p>
<pre>
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
List(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
List(2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10)
List(5, 1, 7, 4, 3, 5, 11, 2, 13, 7, 5, 8, 17, 3, 19, 10)
List(1, 7, 2, 3, 5, 11, 1, 13, 7, 5, 4, 17, 3, 19, 5)
List(7, 2, 3, 1, 11, 1, 13, 7, 1, 4, 17, 3, 19, 1)
List(2, 3, 1, 11, 1, 13, 7, 1, 4, 17, 3, 19, 1)
List(3, 1, 11, 1, 13, 1, 1, 4, 17, 3, 19, 1)
List(1, 11, 1, 13, 1, 1, 2, 17, 3, 19, 1)
List(11, 1, 13, 1, 1, 2, 17, 1, 19, 1)
List(1, 13, 1, 1, 2, 17, 1, 19, 1)
List(13, 1, 1, 2, 17, 1, 19, 1)
List(1, 1, 2, 17, 1, 19, 1)
List(1, 2, 17, 1, 19, 1)
List(2, 17, 1, 19, 1)
List(17, 1, 19, 1)
List(1, 19, 1)
List(19, 1)
List(1)
</pre>
<p>The final list returned will actually look like this:</p>
<pre>1, 2, 3, 2, 5, 1, 7, 2, 3, 1, 11, 1, 13, 1, 1, 2, 17, 1, 19, 1</pre>
<p>Now we need to call this method, and multiply all the numbers to get the smallest number divisible by all numbers from 1 to 20. The numbers reduced to 1 in the above list will of course not have any effect on the result, as they are included in other factors.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> reduceMuls<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">20</span> toList<span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">foldLeft</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_*_</span><span style="color: #F78811;">&#41;</span>
println<span style="color: #F78811;">&#40;</span>res<span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>We need to convert the Seq to a list so it can properly be used in our function. I actually discovered after doing most off the code in this post that I could also do this with a Seq[Int], however it doesn&#8217;t work for how I intend to evolve the code a bit later. What we can do first, is to replace the foldLeft method with the fold left operator, /:. Though it is actually a method rather than an operator, as there are no operators in Scala, just methods. The code is then:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> /<span style="color: #000080;">:</span> reduceMuls<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">20</span> toList<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_*_</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>This post is already quite long, but now I am actually coming to the part I want to demonstrate a bit more here, Scala&#8217;s pattern matching. When we have if/else constructs (though technically the else is missing), they can often be simplified with match expressions. Here is the same method rewritten to use Scala&#8217;s match operator:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> reduceMuls<span style="color: #F78811;">&#40;</span>src<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> src <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">1</span><span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> reduceMuls<span style="color: #F78811;">&#40;</span>rest<span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> a<span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> a<span style="color: #000080;">::</span>reduceMuls<span style="color: #F78811;">&#40;</span>rest map<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">=&gt;</span>if<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">%</span>a<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> x/a <span style="color: #0000ff; font-weight: bold;">else</span> x<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> src
    <span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>The match expressions look a bit similar to Javas switch, but it&#8217;s much more powerful. It takes any object and compares it to the expression in the case statement. The case statement can also use variable names that can then be used in the resulting handler. One important thing here is that for methods you need to handle all cases, which usually ends with a default case at the end. There are partial functions and case classes that allows you to work around this, but I won&#8217;t go into that here. Let&#8217;s look at the cases in the above example. There is also no fall through and breaks. Each handler is separate.</p>
<p>The first cases say the number 1 followed by a list. This will match all lists that have at least 1 element, and the first element is 1. I say 1 element because the rest off the list can be the empty list. The rest keyword then refers to a variable name that is in scope for the handler. For this case, we can drop the 1, and just reduce the rest of the list.</p>
<p>The second case is any value followed by a list of values. This will match all other entries except the empty list. For this we create a new list of a, and then rest divided by a where the values are divisible by a.</p>
<p>The final case handles anything. _ is the wildcard operator for Scala, and this just simply returns the src as is. This will be hit when we try reduceMuls on the empty list, which has no element followed by a tail.</p>
<p>Now we are almost done, but I have one more trick to show first:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> divBy<span style="color: #F78811;">&#40;</span>div<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">%</span>div<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> x/div <span style="color: #0000ff; font-weight: bold;">else</span> x
<span style="color: #0000ff; font-weight: bold;">def</span> reduceMuls<span style="color: #F78811;">&#40;</span>src<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> src <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">1</span><span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> reduceMuls<span style="color: #F78811;">&#40;</span>rest<span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">case</span> a<span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> a<span style="color: #000080;">::</span>reduceMuls<span style="color: #F78811;">&#40;</span>rest map divBy<span style="color: #F78811;">&#40;</span>a<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> src
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>I have added a divBy method here, which takes 2 sets of arguments. A divisor, and a value to divide by. This is Scala&#8217;s way of doing something called Currying. This has a lot of uses, but here we use it in the reduceMuls map to make it more readable. divBy(a) returns a partial function that is missing it&#8217;s last argument, x, before it can be called. This method is then applied for each element in rest using the map function.</p>
<p>Our final program is then:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Euler005 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> divBy<span style="color: #F78811;">&#40;</span>div<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">%</span>div<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> x/div <span style="color: #0000ff; font-weight: bold;">else</span> x
    <span style="color: #0000ff; font-weight: bold;">def</span> reduceMuls<span style="color: #F78811;">&#40;</span>src<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> src <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">1</span><span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> reduceMuls<span style="color: #F78811;">&#40;</span>rest<span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> a<span style="color: #000080;">::</span>rest <span style="color: #000080;">=&gt;</span> a<span style="color: #000080;">::</span>reduceMuls<span style="color: #F78811;">&#40;</span>rest map divBy<span style="color: #F78811;">&#40;</span>a<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> src
    <span style="color: #F78811;">&#125;</span>
    println <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> /<span style="color: #000080;">:</span> reduceMuls<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">20</span> toList<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_*_</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>A bit sorry for this long post, I actually started it over 2 weeks ago at an airport while a bit bored. However, I have been really busy so this post didn&#8217;t get done until now. I will try to get back with more posts more regularily, as I have solved quite a few more Euler problems in Scala already. It&#8217;s also getting easier and easier to think in more Scala like terms for this, producing ever shorter programs faster than I would in Java.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/04/euler-problem-5-in-scala.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler problem 4 in Scala</title>
		<link>http://blog.staale.org/2009/04/euler-problem-4-in-scala.html</link>
		<comments>http://blog.staale.org/2009/04/euler-problem-4-in-scala.html#comments</comments>
		<pubDate>Fri, 03 Apr 2009 10:41:44 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=86</guid>
		<description><![CDATA[The fourth problem in project euler deals with palindromes:


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

One off the main functions we will need for this, is off [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://projecteuler.net/index.php?section=problems&amp;id=4">fourth problem</a> in project euler deals with palindromes:</p>
<blockquote>
<div class="problem_content">
<p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 <img style="vertical-align: middle;" src="http://projecteuler.net/images/symbol_times.gif" border="0" alt="×" width="9" height="9" /> 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.</p></div>
</blockquote>
<p>One off the main functions we will need for this, is off course a method to check if a number is a palindrome. This is easiest to check on strings rather than numbers directly. And a string function would work for all integral types we could want to check (Int, Long, BigInt).</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Util <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> isPalindrome<span style="color: #F78811;">&#40;</span>txt<span style="color: #000080;">:</span> String, s<span style="color: #000080;">:</span>Int, e<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>Boolean <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
        <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>s<span style="color: #000080;">&amp;</span>gt<span style="color: #000080;">;</span>e<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">true</span>
        <span style="color: #0000ff; font-weight: bold;">else</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>txt<span style="color: #F78811;">&#40;</span>s<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">==</span> txt<span style="color: #F78811;">&#40;</span>e<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> isPalindrome<span style="color: #F78811;">&#40;</span>txt,s+<span style="color: #F78811;">1</span>,e-<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">else</span> <span style="color: #0000ff; font-weight: bold;">false</span>
    <span style="color: #F78811;">&#125;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> isPalindrome<span style="color: #F78811;">&#40;</span>txt<span style="color: #000080;">:</span>String<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Boolean <span style="color: #000080;">=</span> isPalindrome<span style="color: #F78811;">&#40;</span>txt,<span style="color: #F78811;">0</span>,txt.<span style="color: #000000;">length</span>-<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">def</span> toStr<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> n.<span style="color: #000000;">toString</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>I have created a separate Util object for this, as I know there are future problems that also deal with palindromes. The code uses 2 pointers, one from the start and one from the end. As long as they point to the same character we move them towards the middle of the string. If the end is less than the start, no conflicts found, and we have a palindrome. Otherwise the number is not a palindrome.</p>
<p>A new concept in this Util class is the implicit def method, that is just a simple converter from Int to String. The implicit tells the Scala compiler that it can use this function for implicit conversion. Implicit conversions are a neat feature off scala that converts expressions to new types if necessary. Here it allows us to call the isPalindrome method with an Int rather than a String. The Compiler sees that there is a mismatch, but it has an implicit conversion in scope that can turn the Int into a String.</p>
<p>So given the following usage:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">isPalindrome<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">91</span> <span style="color: #000080;">*</span> <span style="color: #F78811;">99</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>This would be an error, as isPalindrome expects a String, but we are giving it an Int. The compiler finds the implicit conversion, and changes the code to the following:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">isPalindrome<span style="color: #F78811;">&#40;</span>toStr<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">91</span><span style="color: #000080;">*</span><span style="color: #F78811;">99</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>With the palindrome method in hand, we can now look for ways to find the highest palindrome that is a product of 2 3 digit numbers. This actually provided me with some problems, as I spent some time finding the optimal solution. If we look at the most brute force approach first, we have:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> products <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>a <span style="color: #000080;">&amp;</span>lt<span style="color: #000080;">;</span>- <span style="color: #F78811;">100</span> to <span style="color: #F78811;">999</span><span style="color: #000080;">;</span>b <span style="color: #000080;">&amp;</span>lt<span style="color: #000080;">;</span>- <span style="color: #F78811;">100</span> to <span style="color: #F78811;">999</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> a<span style="color: #000080;">*</span>b
println<span style="color: #F78811;">&#40;</span>products.<span style="color: #000000;">filter</span><span style="color: #F78811;">&#40;</span>isPalindrome<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">toList</span>.<span style="color: #000000;">sort</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_&amp;</span>gt<span style="color: #000080;">;_</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">head</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>The for loop at line 1 will have a iterate from 100 to 999, and for each a iterate b 100 to 999. yield evaluates an expression to return a Seq, in this case off Int. This gives us over 800000 numbers, all the possible products.<br />
Line 2 first filters on all values that are palindromes. isPalindrome(_) is equivalent of (a) =&gt; isPalindrome(a). The filtered list will now just contain the Int values that are palindromes. Next we sort the list, here (_&gt;_) is equivalent of (a,b) =&gt; a &gt; b as a sort method. And finally we pick the first element from the result.</p>
<p>However, we go through too many solutions here that aren&#8217;t necessary. We should instead start from 999*999 and go down, and stop whenver we exceed the highest palindrome earlier found. To do this we are going to take advantage off the filter functions that exists in for loops in Scala. Scala for loops are a lot more powerfull than those we have in Java.</p>
<p>My final solution is thus:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Euler004 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">var</span> max <span style="color: #000080;">=</span> <span style="color: #F78811;">0</span>
    <span style="color: #0000ff; font-weight: bold;">val</span> palindromes <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#123;</span>
        a <span style="color: #000080;">&amp;</span>lt<span style="color: #000080;">;</span>- <span style="color: #F78811;">100</span> to <span style="color: #F78811;">999</span> reverse<span style="color: #000080;">;</span>
        <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">*</span><span style="color: #F78811;">999</span> <span style="color: #000080;">&amp;</span>gt<span style="color: #000080;">;</span> max<span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span>
        b <span style="color: #000080;">&amp;</span>lt<span style="color: #000080;">;</span>- a to <span style="color: #F78811;">999</span> reverse<span style="color: #000080;">;</span>
        c <span style="color: #000080;">=</span> a<span style="color: #000080;">*</span>b<span style="color: #000080;">;</span>
        <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>c <span style="color: #000080;">&amp;</span>gt<span style="color: #000080;">;</span> max <span style="color: #000080;">&amp;</span>amp<span style="color: #000080;">;&amp;</span>amp<span style="color: #000080;">;</span> isPalindrome<span style="color: #F78811;">&#40;</span>c<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
    <span style="color: #F78811;">&#125;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> <span style="color: #F78811;">&#123;</span>max<span style="color: #000080;">=</span>c<span style="color: #000080;">;</span>max<span style="color: #F78811;">&#125;</span>
    println <span style="color: #F78811;">&#40;</span>palindromes.<span style="color: #000000;">reverse</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>We here need to have a variable to keep track off the max value found so far. The for expression now expands across multiple lines. On line 3 we say to iterate a from 999 to 100, so every following expression will be evaluated for each value off a from 999 to 100. Next we have an if, this checks if a*999 is bigger than our currently found max. If it isn&#8217;t, we don&#8217;t need to check anything else. This serves as a guard for the rest of the expressions in the for loop. On line 5 we iterate b from 999 to a, and on line 6 we just store the product in c. Finally we have a guard to check that c is bigger than max, and it is a palindrome.</p>
<p>In the yield we now have a block instead of just a single expression. This is because we need to assign max first, then return max.</p>
<p>Now we have a list of palindromes in increasing order. Any product found less than the highest palindrome will be skipped. To find the actual result, we just reverse the list and print out the first entry.</p>
<p>I did spend quite some time on this task to get a good solution. I have a faster one using while loops, but it doesn&#8217;t look as elegant. Additionally I read parts off the for loop segment in the Scala book yesterday, so I was interested in trying out some off the principles on this problem. I was originally planning on doing this with actors, just to see how they worked out, but I haven&#8217;t yet read fully about them. Perhaps I will deal with a later problem using actors.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/04/euler-problem-4-in-scala.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler problem 3 in Scala</title>
		<link>http://blog.staale.org/2009/03/euler-problem-3-in-scala.html</link>
		<comments>http://blog.staale.org/2009/03/euler-problem-3-in-scala.html#comments</comments>
		<pubDate>Wed, 25 Mar 2009 13:28:13 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=64</guid>
		<description><![CDATA[The third project Euler problem is about finding the largest divisor for a single number:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143
One small &#8220;problem&#8221; here is that the number 600851475143 exceeds Integer.MAX_VALUE which is 2147483647, so we have to use either Long or [...]]]></description>
			<content:encoded><![CDATA[<p>The third project Euler problem is about finding the largest divisor for a single number:</p>
<blockquote><p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143</p></blockquote>
<p>One small &#8220;problem&#8221; here is that the number 600851475143 exceeds Integer.MAX_VALUE which is 2147483647, so we have to use either Long or BigInt. I went for BigInt for this one. The algorithm I choose is pretty simple:</p>
<p>Take the number n, and divisor d:</p>
<ul>
<li>if n mod d is 0, divide n by d and check again</li>
<li>if n is larger than d, increase d by 1 and check again</li>
<li>d is the answer</li>
</ul>
<p>In Scala code, the method turns out as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> largestDivisor<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>BigInt, d<span style="color: #000080;">:</span>BigInt<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>BigInt <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">%</span>d <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> largestDivisor<span style="color: #F78811;">&#40;</span>n/d,d<span style="color: #F78811;">&#41;</span> 
    <span style="color: #0000ff; font-weight: bold;">else</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">&gt;</span>d<span style="color: #F78811;">&#41;</span> largestDivisor<span style="color: #F78811;">&#40;</span>n,d+<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span> 
    <span style="color: #0000ff; font-weight: bold;">else</span> d
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">def</span> largestDivisor<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>BigInt<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> BigInt <span style="color: #000080;">=</span> largestDivisor<span style="color: #F78811;">&#40;</span>n,<span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>We have a convinience method here to help us out, as we always start the divisor with a value off 2. If we started with 1 we would have an endless loop, as all numbers mod 1 is 0. It&#8217;s then just a matter of printing out the result.</p>
<p>Again we are using tail recursion, which Scala will rewrite to a loop instead. To look at the actual result off the code, I ran the resulting class file through <a href="http://www.varaneckas.com/jad">jad</a>, and got the following result:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> BigInt largestDivisor<span style="color: #009900;">&#40;</span>BigInt n, BigInt d<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">do</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">;</span> BoxesRunTime.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>n.$percent<span style="color: #009900;">&#40;</span>d<span style="color: #009900;">&#41;</span>, BoxesRunTime.<span style="color: #006633;">boxToInteger</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> n <span style="color: #339933;">=</span> n.$div<span style="color: #009900;">&#40;</span>d<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>n.$greater<span style="color: #009900;">&#40;</span>d<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                d <span style="color: #339933;">=</span> d.$plus<span style="color: #009900;">&#40;</span>BigInt$.<span style="color: #006633;">MODULE</span>$.<span style="color: #006633;">int2bigInt</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">else</span>
                <span style="color: #000000; font-weight: bold;">return</span> d<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In line 3 we see the continual division off n/d as long as n%d == 0. This corresponds exactly to my Scala code in line 2, recursivly calling it self while dividing n by d. Line 4-7 corresponds to line 3-4 in the Scala progam, increasing d by 1 if d is less than n, or returning d. By running my Scala compiled class file through jad, I am able to exactly see how Scala converts tail recursion to loop code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/03/euler-problem-3-in-scala.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler problem 2 in Scala</title>
		<link>http://blog.staale.org/2009/03/euler-problem-2-in-scala.html</link>
		<comments>http://blog.staale.org/2009/03/euler-problem-2-in-scala.html#comments</comments>
		<pubDate>Tue, 24 Mar 2009 15:55:30 +0000</pubDate>
		<dc:creator>Staale</dc:creator>
				<category><![CDATA[Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://blog.staale.org/?p=53</guid>
		<description><![CDATA[The 2nd project Euler problem is also rather trivial:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, &#8230;
Find the sum of all the even-valued terms in the sequence [...]]]></description>
			<content:encoded><![CDATA[<p>The 2nd project Euler problem is also rather trivial:</p>
<blockquote><p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p>
<p style="text-align: center;">1, 2, 3, 5, 8, 13, 21, 34, 55, 89, &#8230;</p>
<p>Find the sum of all the even-valued terms in the sequence which do not exceed four million.</p></blockquote>
<p>Creating a fibonacci method in Scala is trivial:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>Int <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>n <span style="color: #000080;">&lt;=</span> <span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">1</span> <span style="color: #0000ff; font-weight: bold;">else</span> fib<span style="color: #F78811;">&#40;</span>n-<span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span>+fib<span style="color: #F78811;">&#40;</span>n-<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>Since this is a recursive function, we need to explicitly declare the return type, as Scala can&#8217;t infer it from the method body alone. The method is however badly recursive. Scala does support tail recursion, that is recursion when the last statement off the method calls itself. However here the method calls itself before the end, so tail recursion can&#8217;t be used. This causes an exponential row off calls. Rewriting the method so it employs tail recursion, it looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>Int, a<span style="color: #000080;">:</span>Int, b<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>Int <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> a <span style="color: #0000ff; font-weight: bold;">else</span> fib<span style="color: #F78811;">&#40;</span>n-<span style="color: #F78811;">1</span>, b, a+b<span style="color: #F78811;">&#41;</span>
<span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>Int <span style="color: #000080;">=</span> fib<span style="color: #F78811;">&#40;</span>n, <span style="color: #F78811;">1</span>, <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>The 2nd method here is just a shorthand for the first. We recursivly call ourselves with decreasing n until n reaches 0, in which case argument a will hold the correct answer. Since this is a tail recursive call, Scala is able to rewrite it into a loop instead, thus avoiding deep stack frames and StackOverflow exceptions.</p>
<p>However, calculating increasing fibonacci numbers until we reach the max of 4 million is not effective. We keep throwing away the calculations from each step even though we could use it for the next number. What we need instead is a method for iterating over all the fibonacci numbers. In python this would be a generator functions, but atm. I don&#8217;t know the equivalent in Scala. Instead I went for a method creating a list of Fibonacci numbers:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>max<span style="color: #000080;">:</span> Int, a<span style="color: #000080;">:</span> Int, b<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>a+b <span style="color: #000080;">&lt;</span> max<span style="color: #F78811;">&#41;</span> a+b <span style="color: #000080;">::</span> fib<span style="color: #F78811;">&#40;</span>max, b, a+b<span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">else</span> List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>max<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> fib<span style="color: #F78811;">&#40;</span>max, <span style="color: #F78811;">0</span>, <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>The 2nd method is the one we will normally call, which calls to the first to do the actual work. Here we use the List concatenation operation in scala, ::. This will prepend the expression on the left (a+b) to the list on the right (fib(max, b, a+b)). This is because the default Lists in Scala are immutable LinkedLists, so adding to the start is a cheap operation. </p>
<p>With the method for generating fibonacci numbers in hand, it&#8217;s easy to calculate the sum off all even fibonacci numbers below 4 million. We just need to filter out the even numbers, then appply a reduce function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;">println<span style="color: #F78811;">&#40;</span>fib<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">4000000</span><span style="color: #F78811;">&#41;</span> filter<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_%</span>2<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> reduceRight<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>The full program then becomes:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Euler002 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>max<span style="color: #000080;">:</span> Int, a<span style="color: #000080;">:</span> Int, b<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
        <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>a+b <span style="color: #000080;">&lt;</span> max<span style="color: #F78811;">&#41;</span> a+b <span style="color: #000080;">::</span> fib<span style="color: #F78811;">&#40;</span>max, b, a+b<span style="color: #F78811;">&#41;</span>
        <span style="color: #0000ff; font-weight: bold;">else</span> List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
    <span style="color: #F78811;">&#125;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fib<span style="color: #F78811;">&#40;</span>max<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> fib<span style="color: #F78811;">&#40;</span>max, <span style="color: #F78811;">0</span>, <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span>
&nbsp;
    println<span style="color: #F78811;">&#40;</span>fib<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">4000000</span><span style="color: #F78811;">&#41;</span> filter<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_%</span>2<span style="color: #000080;">==</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> reduceRight<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>   
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>A note of caution here. All my methods use Int, which will overflow quickly for fibonacci numbers. If larger numbers are needed, use Long or BigInt. BigInt has all the common math operations overloaded, so it&#8217;s just as easy to use as Int in the above code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.staale.org/2009/03/euler-problem-2-in-scala.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
