# Duncan’s blog

## October 27, 2008

### Project Euler: problem 9

Problem 9:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

This one took a few goes to figure out. Initially I’d made a mistake in my loop, which meant I wasn’t getting back any successful results. Then I had a brainwave why this might be (before I realised my mistake): a and b (and even c) could be negative!

I then wasted time coming up with a clever nested loop that allowed me to generate all the variations of +/- a, b and c. If I’d just spent some time reading up on natural numbers, I’d have discovered they have to be positive.

When that didn’t give me the results I wanted, I went back to my code, realised my earlier mistake and corrected it (I’d not been incrementing a and b properly).

```<cfloop index="a" from="1" to="500">
<cfloop index="b" from="1" to="500">
<cfset pythagoras = (a * a) + (b * b)>
<cfset c = Sqr(pythagoras)>

<cfif c EQ Round(c)>
<!--- it's an integer --->
<cfset sum = a + b + c>
<cfif sum EQ 1000>
<cfset product = a * b * c>
<cfoutput>
#a# + #b# + #c# = #sum#<br>
#a# * #b# * #c# = <strong>#product#</strong>
</cfoutput>
<cfabort>
</cfif>
</cfif>
</cfloop>
</cfloop>
```

Figure out what a2 + b2 is. Is it an integer? If so, add a, b and c. Do they add up to 1000? If so, multiply them together, and then stop.

## October 26, 2008

### Project Euler: problem 8

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , ,

Problem 8:

Find the greatest product of five consecutive digits in the 1000-digit number.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

This time it doesn’t give us any smaller test case, so we’ll need to just trust our code is correct. I found this one fairly simple, maybe because there’s no difficult maths involved. I expect you could probably code a more interesting solution. For example you could eliminate any set of 5 digits with a zero. You could also keep a tally of digits you’ve already tried, e.g. for the first two sets of 5 digits, you could have:
tally[1] = 13677;
tally[2] = 11367;
etc. This way you could eliminate the need to do the multiplication for anything you’ve already done. It’s doubtful there’d be any advantage in doing this, for this sort of number. Might be more useful on larger numbers.

```<cfsavecontent variable="bigNumber">
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
</cfsavecontent>

<cfset bigString = "">

<cfset max = 0>

<!--- first, turn this into a proper string --->
<cfloop index="i" list="#bigNumber#" delimiters="#Chr(13)##Chr(10)#">
<cfset bigString = bigString & i>
</cfloop>

<!--- loop through string --->
<cfloop index="i" from="1" to="996">
<!--- get our 5 digits --->
<cfset a = Mid(bigString, i, 1)>
<cfset b = Mid(bigString, i+1, 1)>
<cfset c = Mid(bigString, i+2, 1)>
<cfset d = Mid(bigString, i+3, 1)>
<cfset e = Mid(bigString, i+4, 1)>

<cfset sum = a * b * c * d * e>
<cfoutput>#a# * #b# * #c# * #d# * #e# = #sum#</cfoutput><br>

<cfif sum GT max>
<cfset max = sum>
</cfif>
</cfloop>

<cfoutput>#max#</cfoutput>
```

I decided to treat the number given exactly as it was, and not to manually eliminate the linebreaks. Using <cfsavecontent>, we can then treat it as a list with CRLF linebreaks. I turn the whole thing into a string (alternatively I could have just used Replace to get rid of the linebreaks). Then I loop through it, up to 5 digits before the end of the string. Using Mid() to get each number out of the string, do the multiplication, and compare it to whatever is the maximum value so far.

Another way along this line might have been to turn the whole thing into a 1000 element array, and loop through the array. Typically array methods in Coldfusion will work faster than list and string methods that do the same thing.

## October 25, 2008

### Project Euler: problem 7

Problem 7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

Prime numbers again, good job I spent so long trying various things out on problem 3. I just copied the IsPrime function I did then (except removed the custom Mod function and just used CF’s MOD, as we’re dealing with smaller numbers here).

I’m using a brute force method of continually looping, building up an array of primes, until we get to the 10001st one. This time, as we know primes start at 2, but are odd after that, I decided to pre-populate my array with 2, and then loop in steps of 2 from 3 upwards.

```<cfset primes = ArrayNew(1)>
<cfset limit = 10001>
<cfset done = 0>
<cfset i = 1>
<cfset ArrayAppend(primes, 2)>

<cfscript>
function isPrime(x)
{
var isPrime = true;
var i = 0;

if (x LT 2)
{
return false;
}

if ((NOT x MOD 2) AND (x GT 2))
{	// a multiple of 2, but not 2 itself
return false;
}

for (i = 3; i LTE SQR(x); i = i + 2)
{
if (NOT x MOD i)
{	// found a factor of x
return false;
}
}

return isPrime;
}
</cfscript>

<cfloop condition="NOT done">
<cfset i = i + 2>

<cfif IsPrime(i)>
<cfset ArrayAppend(primes, i)>

<cfif ArrayLen(primes) EQ limit>
<cfset done = 1>
</cfif>
</cfif>
</cfloop>

<cfoutput>
#primes[limit]#
</cfoutput>
```

## October 24, 2008

### Project Euler: problem 6

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , ,

Problem 6:

The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 – 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

A nice easy one this time. Basically we want to loop from 1 to 100. Use two variables. Sum1 = a sum of the values of 1-100 squared. Sum2 = a sum of the values of 1-100 (not squared). At the end of the loop, square Sum2. Subtract Sum1 from Sum2.

```<cfset sum1 = 0>
<cfset sum2 = 0>

<cfloop index="i" from="1" to="100">
<cfset sum1 = sum1 + (i * i)>

<cfset sum2 = sum2 + i>
</cfloop>

<cfset sum2 = sum2 * sum2>
<cfset difference = sum2 - sum1>

<cfoutput>
sum1: #sum1#<br>
sum2: #sum2#<br>
difference: #difference#<br>
</cfoutput>
```

The only thing to watch out for is where it asks for “the difference“. I just did a straight subtraction. However, in other problems where it might be harder to guess which of two values would be greater, this should probably be wrapped in the Abs() function, to prevent a negative value being returned.

## October 23, 2008

### Project Euler: problem 5

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , ,

This was the problem that first attracted my attention to Project Euler, after reading about it on the Daily WTF.

Problem 5:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

Rather than try doing it with multiple nested MOD statements, I thought it made more sense to do it properly as a loop. Took me a few goes to get this one right. I kept going into infinite loops because I was stepping too far; the reason I don’t like using while loops.

```<cfset found = 0>
<cfset step = 20>
<cfset factor = step - 1>
<cfset i = step>

<cfoutput>#i#<br></cfoutput>
<cfif NOT i MOD factor>
<!--- factor goes into i exactly --->
<hr>
<!--- it must be a multiple of this number --->
<cfif factor EQ 11>
<cfset found = 1>
<cfbreak>
</cfif>

<cfset factor = factor - 1>
<!--- each successful iteration, step down once --->
<cfset step = i>
<cfoutput>step = #step#, factor = #factor#<br></cfoutput>
<cfelse>
<cfset i = i + step>
</cfif>
</cfloop>

<cfoutput><strong>#i#</strong></cfoutput>
```

There’s a little bit of redundancy in the loop; as I’m using <cfbreak>, I don’t need to also set my ‘found’ flag to true, as the loop will end anyway. In fact the loop might just as well say condition=”1 GT 0″, as I’m wanting to loop forever until we get that last factor.

In the document you can access after solving this problem, it goes into using prime factors and logarithms and various complicated mathematical ways to do the same thing, but I like to keep it simple.

Basically we start at 20 (although I could have started at 2520), incrementing by 20 each time. First try doing MOD 19 (we don’t need to bother with MOD 20 because we already know it’s a multiple of 20). Once we’ve got a number that both 19 and 20 are factors for, we increase our increment from 20 to whatever this number is. Repeat in that fashion until we hit a number that satisfies MOD 11. We don’t need to bother with 1-10, because all those numbers are already factors of numbers from 11-20.

## October 22, 2008

### Project Euler: problem 4

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , , ,

Problem 4:

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

Find the largest palindrome made from the product of two 3-digit numbers.

A nice simple one this time, at least if you’re using ColdFusion. Basically there are two steps to this:

1. Test to see if a number is a palindrome
2. Loop through the numbers
```<cfscript>
function isPalindrome(x)
{
if (x EQ Reverse(x))
return true;
else
return false;
}
</cfscript>

<cfset palindrome = 0>

<cfloop index="i" from="100" to="999">
<cfloop index="j" from="100" to="999">
<cfset x = i * j>
<cfif x GT palindrome AND IsPalindrome(x)>
<cfset palindrome = x>
</cfif>
</cfloop>
</cfloop>

<cfoutput>#palindrome#</cfoutput>
```

Initially I split the number into two halves, reversed one half and compared it. Then I realised I could have just reversed the number itself to get the same result.

Then a pair of nested loops for doing the multiplication. There’s a bit of duplication, e.g. when i=900 and j=950, will give us the same result as when i=950 and j=900. However I’m guessing it’s not worth the effort to try and factor out those.

The only other thing worth mentioning is the order of the clauses in my if statement. Coldfusion uses lazy evaluation, meaning in a statement like IF A OR B, it will first evaluate A, and then only if A is false will it evaluate B. So I guessed that using the GT comparison is a quicker operation than running through my IsPalindrome function. So by moving that function call to the second clause, we only need to run it on those numbers that are bigger than what we already have.

## October 21, 2008

### Project Euler: problem 3

Problem 1 took a couple of minutes, Problem 2 not much longer than that. Problem 3 took me several hours over a few days to work out! Hopefully some of the work I’ve done will stand me in stead for future problems involving prime numbers.

Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Initially I thought to use a Sieve of Eratosthenes to find all the primes less than 600851475143 (the limit). Then check which of those primes were its factors. This worked fine for 13195, but timed out on the larger number.

Then I tried doing the opposite: finding all the factors of the limit, then checking which of them are prime. Again, it timed out on the big number.

Then I read somewhere that all primes, except 2 and 3, are either +1 or -1 from a multiple of 6. e.g. 97 is prime. 97-1 = 96, which is 6 x 16. So I tried using that to test for things that might be prime, before applying the more time consuming check to see if it actually was prime. Again, no dice.

It’s worth mentioning that I’m doing this on an old CF 5 server. Some of my earlier attempts might have ran ok on CFMX. Also I’d have had the option to slip into Java, perhaps for casting the limit to a long int. And I’d be able to use the CFFunction tag rather than embed functions into CFScript.

After reading up a bit more, I learned that all I had to do was find the first prime factor, then divide the limit by that, and find the prime factor of whatever that is, and so on. Doing this you shouldn’t need to go any higher than the square root of your number each time.

So for instance, using 13195 as our limit:

• loop through 13195 until find the first prime factor
• it’s 5. store that in an array
• divide 13195 by 5 = 2639
• loop through 2639 until find the first prime factor
• it’s 7. add that to our array
• divide 2639 by 7 = 377
• loop through 377 until find the first prime factor
• it’s 13. add that to our array
• divide 377 by 13 = 29.
• 29′s larger than the square root of 377, so we’ll stop there
• the next prime factor of 2639 is 29 (coincidentally). add that to our array
• divide 2639 by 29 = 91
• 91′s larger than the square root of 2639, so we’ll stop there
• there are no more prime factors of 13195

So, the best way to tackle this is with a recursive function. Always fun to get your head around. Rather than try and pass an array of primes as a parameter to the function, I simply set the array in the variables scope, and continually appended to it. Not how I’d normally do it (but then I don’t normally use recursion if I can help it), but I saw an article on recursion in coldfusion which did something similar, using the variables scope.

I wrote my own IsPrime function, and I had to use the ProperMod UDF from CFLib. The reason for this is that Coldfusion can only handle 32-bit ints, i.e. between -2,147,483,648 and 2,147,483,647. Anything outwith that I think it converts to a string. The MOD statement expects an int, not a string, so it throws an error. In some cases you can still use this value for doing mathematical functions on, e.g. I had no problem finding a square root, even though the Sqr() function also expects an integer. If I was using CFMX, I could probably have used Java to cast to a long integer.

All primes except 2 are odd, so when looping we can go in steps of 2 rather than the normal 1. I sort of deal with this a bit cack-handed, and for the parent loop, it does it in steps of 1. Perhaps if I used a while loop instead of a for loop, I could have got this code better.

Here’s the code. It’s far from optimal, but it works!

```<cfset limit = 600851475143>
<cfset primes = ArrayNew(1)>

<cfscript>
function isPrime(x)
{
var isPrime = true;
var i = 0;

if (x LT 2)
{
return false;
}

if ((NOT ProperMod(x, 2)) AND (x GT 2))
{	// a multiple of 2, but not 2 itself
return false;
}

for (i = 3; i LTE SQR(x); i = i + 2)
{
if (NOT ProperMod(x, i))
{	// found a factor of x
return false;
}
}

return isPrime;
}

/**
* Computes the mathematical function Mod(y,x).
*
* @param y      Number to be modded.
* @param x      Devisor.
* @return Returns a numeric value.
* @author Tom Nunamaker (tom@toshop.com)
* @version 1, February 24, 2002
*/
function ProperMod(y,x) {
var modvalue = y - x * int(y/x);

if (modvalue LT 0) modvalue = modvalue + x;

Return ( modvalue );
}

function findPrimes(x,y)
{
/*Find the first prime factor of limit.
Divide the limit by that factor.
Recursively, find the first prime factor of that number
(not including the previous number we already found).  etc.
These are all the prime factors of limit.  */
// x = limit
// y = where to start from
var i = 0;
var j = 0;
var step = 2;

if (y EQ 2)
step = 1;

for (i = y; i LT SQR(x); i = i + step)
{
if ((NOT ProperMod(x, i)) AND IsPrime(i))
{	// i is a factor of x, and it's prime
if (NOT ListFind(ArrayToList(variables.primes), i))
{	// it's not already in our array of primes
ArrayAppend(variables.primes, i);
j = x / i;
if (i+1 GT SQR(j))
{	// is there any point carrying on?
if (i GT 2)
findPrimes(j, i+2);
else
findPrimes(j, i+1);
}
}
}
}
}
</cfscript>

<cfset findPrimes(limit, 2)>
<cfdump var="#primes#">
```

## October 20, 2008

### Project Euler: problem 2

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , , ,

Project Euler problem 2:

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Again, it’s important to read the spec carefully. “do not exceed four million“, i.e. up to and including 4,000,000.

Here’s my code:

```<cfset sum = 0>
<cfset fibonacci = 1>
<cfset old1 = 0>
<cfset old2 = 1>

<cfloop condition="fibonacci LTE 4000000">
<cfset fibonacci = old1 + old2>
<cfset old1 = old2>
<cfset old2 = fibonacci>

<cfif NOT fibonacci MOD 2>
<cfset sum = sum + fibonacci>
</cfif>
</cfloop>

<cfoutput>
<p><strong>#sum#</strong></p>
</cfoutput>
```

This time we’re using a While loop, not something I do that often. Using NOT fibonacci MOD 2 gives us all the even values. The only tricky part was working out that I had to use two variables to store the progression of the Fibonacci series. So basically we loop through the entire Fibonacci series up to 4,000,000, keeping a sum of the even values in a separate variable.

## October 19, 2008

### Project Euler: problem 1

Filed under: Coldfusion,Project Euler — duncan @ 11:07 am
Tags: , , , ,

Initially I wasn’t going to blog about the first two Project Euler problems, because I thought they were too simple. However I read something elsewhere encouraging people to blog about even simple coding things, because there’ll be someone else who’s not at that level that could benefit from reading it.

Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

So, this seemed pretty simple. I liked the fact they gave a test case, so you could run against that before trying to get the answer for 1000.

Here’s the code I used:

```<cfset sum = 0>
<cfoutput>
<cfloop index="i" from="1" to="999">
<cfif (NOT i MOD 3) OR (NOT i MOD 5)>
<cfset sum = sum + i>
#i#<br>
</cfif>
</cfloop>

<strong>#sum#</strong>
</cfoutput>```

If I modify the loop to run to 9, it outputs
3
5
6
9
23
as expected.

Some things to note:
We’re only running up to 999, not 1000, as it states “below 1000“. Make sure and read your specification carefully!

I guess some people might not be familiar with the MOD statement in Coldfusion, or Modulus in general. Ben Nadel wrote a great article explaining it. Basically x MOD y says, divide x by y, but only give me the remainder. e.g. 10 MOD 3 = 1, because 3 goes into 10 three times, remainder 1. So if we say NOT i MOD 3, we mean this is a multiple of 3, i.e. there is no remainder.

There’s a version called ProperMod in the CFLib which does it better, because it allows division of real numbers as well as integers. It also handles cases where your integer value is larger than Coldfusion will allow (which came in useful for Project Euler problem 3 – more on that later).

I could have written my if statement as:

`<cfif NOT (i MOD 3 AND i MOD 5)>`

because (NOT A) OR (NOT B) = NOT (A AND B). This can be illustrated with some Venn diagrams (coincidentally very similar to Euler diagrams). In each diagram, it’s the cross-hatched part we’re interested in. [Does anyone know some decent free software for creating Venn diagrams like this?]

I preferred to keep it as two separate clauses just for readability.

This solution worked, but the PDF that you get after submitting the correct answer discusses another way to do it. That would be to have one function that sums the values of x MOD y. So you’d do SumOfValues(3) + SumOfValues(5) – SumOfValues(15).

## October 17, 2008

### Project Euler

Filed under: Coldfusion,Project Euler — duncan @ 11:35 pm
Tags: , , , ,

"… a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems."

I found the site from a story on the Daily WTF, showing a less than optimal way someone had solved one of the Euler problems for a job interview test.

I thought it might be interesting to see how many of these I could do in CFML. Both to increase my basic mathematics knowledge, and improve my Coldfusion.

Once you register with the site, you can submit your answer for any problem and it’ll log if you get it correct. It’ll also give you access to a forum where people discuss the problem, and have a PDF outlining ways you could have tackled it.

So far I’ve just managed the first two and still working on the third.

1. Find the sum of all the multiples of 3 or 5 below 1000.
Simply a case of looping and using the MOD function.

2. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
Again, looping and using MOD. The only tricky part is getting your head round how many variables you’ll need to use to store values as you progress through the Fibonacci series.

It seems that, from reading the PDFs after completing, and from how I’m getting on so far with the third puzzle, there is more than one way to solve these, and the brute force method of looping through all values isn’t going to be the most efficient. Many of the problems seem to deal with very large numbers, which could pose interesting challenges for Coldfusion. When you register, they have a list of programming languages you can choose from; CFML wasn’t listed, although I’ve requested that they add it. The most popular ones seem to be C/C++, Python, Java, C# and Haskell, although everything from Ada to Prolog is represented.

« Previous Page

Theme: Rubric. Blog at WordPress.com.