<?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>stealthcopter.com &#187; project euler</title>
	<atom:link href="http://www.stealthcopter.com/blog/tag/project-euler/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stealthcopter.com/blog</link>
	<description>Android, Linux, Python and stealthcopters</description>
	<lastBuildDate>Sat, 24 Jul 2010 00:01:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Python: Highest common factor of two numbers</title>
		<link>http://www.stealthcopter.com/blog/2009/12/python-highest-common-factor/</link>
		<comments>http://www.stealthcopter.com/blog/2009/12/python-highest-common-factor/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 12:10:42 +0000</pubDate>
		<dc:creator>mat</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[computational]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://www.stealthcopter.com/blog/?p=228</guid>
		<description><![CDATA[Finding the highest common factor is useful in mathematics and cryptography. It would be computationally expensive to calculate all the common factors of two numbers and then compare to find the highest factor in common. Instead (as usual) there is a mathematical theory that can be used to speed up this process, in this case [...]]]></description>
			<content:encoded><![CDATA[<p>Finding the highest common factor is useful in mathematics and cryptography. </p>
<p>It would be computationally expensive to calculate all the common factors of two numbers and then compare to find the highest factor in common. Instead (as usual) there is a mathematical theory that can be used to speed up this process, in this case it&#8217;s the <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm">Euclidean algorithm</a>.</p>
<p>The Euclidean algorithm subtracts the smaller number from the larger number, then using this new number and the smaller number repeats this process until the numbers are equal and hence the subtraction goes to zero. This is the highest common factor.</p>
<p><strong>Example:</strong><br />
Find the highest common factor of 252 and 105</p>
<blockquote><p>
252-105=147<br />
147-105=42<br />
105-42=63<br />
63-42=21<br />
42-21=21<br />
21-21=0
</p></blockquote>
<p>Below is the python code to preform this </p>
<pre name="code" class="python">
def hcf(no1,no2):
	while no1!=no2:
		if no1>no2:
			no1-=no2
		elif no2>no1:
			no2-=no1
	return no1
</pre>
<p>This method is quite quick even and scales well for larger numbers. If you know of a faster method or can see any improvements to make then please let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stealthcopter.com/blog/2009/12/python-highest-common-factor/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Python: Factors of a number</title>
		<link>http://www.stealthcopter.com/blog/2009/11/python-factors-of-a-number/</link>
		<comments>http://www.stealthcopter.com/blog/2009/11/python-factors-of-a-number/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 11:32:46 +0000</pubDate>
		<dc:creator>mat</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[computational]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://www.stealthcopter.com/blog/?p=195</guid>
		<description><![CDATA[Project Euler often requires the factors of a number to be found, here is the function I have written for that purpose. def factors(n): fact=[1,n] check=2 rootn=sqrt(n) while check&#60;rootn: if n%check==0: fact.append(check) fact.append(n/check) check+=1 if rootn==check: fact.append(check) fact.sort() return fact As always any help in speeding up my function would be appreciated. I think it [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/">Project Euler</a> often requires the factors of a number to be found, here is the function I have written for that purpose.</p>
<pre name="code" class="python">
def factors(n):
	fact=[1,n]
	check=2
	rootn=sqrt(n)
	while check&lt;rootn:
		if n%check==0:
			fact.append(check)
			fact.append(n/check)
		check+=1
	if rootn==check:
		fact.append(check)
        fact.sort()
	return fact
</pre>
<p>As always any help in speeding up my function would be appreciated. I think it could be improved using a sieve method or by checking if its divisible by 2 first then using check+=2 starting at 3 to improve the speed of the loop by a factor of 2.</p>
<p>Below is a the commented version to help explain what&#8217;s going on if it&#8217;s not clear.</p>
<pre name="code" class="python">
def factors(n):
	# 1 and n are automatically factors of n
	fact=[1,n]
	# starting at 2 as we have already dealt with 1
	check=2
	# calculate the square root of n and use this as the
	# limit when checking if a number is divisible as
	# factors above sqrt(n) will already be calculated as
	# the inverse of a lower factor IE. finding factors of
	# 100 only need go up to 10 (sqrt(100)=10) as factors
	# such as 25 can be found when 5 is found to be a
	# factor 100/5=25
	rootn=sqrt(n)
	while check&lt;rootn:
		if n%check==0:
			fact.append(check)
			fact.append(n/check)
		check+=1
	# this line checks the sqrt of the number to see if
	# it is a factor putting it here prevents it appearing
	# twice in the above while loop and putting it outside
	# the loop should save some time.
	if rootn==check:
		fact.append(check)
	# return an array of factors sorted into numerial order.
        fact.sort()
	return fact
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stealthcopter.com/blog/2009/11/python-factors-of-a-number/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Python: palindrome checking function</title>
		<link>http://www.stealthcopter.com/blog/2009/09/python-palindrome-checking-function/</link>
		<comments>http://www.stealthcopter.com/blog/2009/09/python-palindrome-checking-function/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 18:28:24 +0000</pubDate>
		<dc:creator>mat</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://www.stealthcopter.com/blog/?p=134</guid>
		<description><![CDATA[I created a reasonable palindrome checking function in python. Method 1 def ispalindrome(num): n=str(num) while len(n)&#62;1: print n if n[0]!=n[-1]: return 0 n=n[1:-1] return 1 I thought that it would be faster avoiding a string conversion, and to somehow use the modulus (modulo) function. However when I came to write it, I found it quite [...]]]></description>
			<content:encoded><![CDATA[<p>I created a reasonable palindrome checking function in python.</p>
<p><strong>Method 1</strong></p>
<pre name="code" class="python">
def ispalindrome(num):
	n=str(num)
	while len(n)&gt;1:
		print n
		if n[0]!=n[-1]:
			return 0
		n=n[1:-1]
	return 1
</pre>
<p>I thought that it would be faster avoiding a string conversion, and to somehow use the modulus (modulo) function. However when I came to write it, I found it quite difficult to code, and I&#8217;m sure there must be a better way.</p>
<p><strong>Method 2</strong></p>
<pre name="code" class="python">
def ispalindrome2(num):
	l=1
	while num/10**l&gt;=1.0:
		l+=1
	r=0
	d=[]
	for i in range(1,l+1):
		p=num%10**i-r
		r+=p
		p=p/10**(i-1)
		d.append(p)

	for i in range(0,l/2):
		if d[i]!=d[-i-1]:
			return 0
	return 1
</pre>
<p>Doing the speed tests show that Method 1 is over 5.2 times faster than Method 2. </p>
<pre>
Method 1
0.355437994003 Seconds elapsed
Method 2
1.85815691948 Seconds elapsed
</pre>
<p><strong>Update: Mike of <a href="http://www.mikemeat.co.uk/blog">mikemeat</a> sent me his method using slices (Method 3) and I adapted it slight (Method 4), then shortly after I realised it could be even more efficient by not needing to differentiate between even and odd strings (Method 5).</strong></p>
<p><strong>Method 3</strong></p>
<pre name="code" class="python">
def ispalindrome3(x):
    z = str(x)
    if len(z)%2 == 0 and z[:len(z)/2]==z[-len(z)/2:][::-1]:
       return 1
    if len(z)%2 != 0 and z[:(len(z)- 1)/2]==z[(-len(z) + 1)/2:][::-1]:
       return 1
    else:
	return 0
</pre>
<p><strong>Method 4</strong></p>
<pre name="code" class="python">
def ispalindrome4(x):
	z = str(x)
	if z[:len( z)/2]==z[len( z)/2+len( z)%2:][::-1]:
		return 1
	return 0
</pre>
<p><strong>Method 5</strong></p>
<pre name="code" class="python">
def ispalindrome5(x):
	z = str(x)
	l=len(z)/2
	if z[:l]==z[-l:][::-1]:
		return 1
	return 0
</pre>
<pre>
Method 1
0.357168912888 Seconds elapsed
Method 2
1.83943104744 Seconds elapsed
Method 3
0.179126977921 Seconds elapsed
Method 4
0.179482936859 Seconds elapsed
Method 5
0.149376153946 Seconds elapsed
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stealthcopter.com/blog/2009/09/python-palindrome-checking-function/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Python: sum of digits in a string</title>
		<link>http://www.stealthcopter.com/blog/2009/09/python-sum-of-digits-in-a-string/</link>
		<comments>http://www.stealthcopter.com/blog/2009/09/python-sum-of-digits-in-a-string/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 03:29:49 +0000</pubDate>
		<dc:creator>mat</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://www.stealthcopter.com/blog/?p=127</guid>
		<description><![CDATA[I have a function I wrote for a project euler that calculates the sum of the digits in a number. This is my first attempt which simply converts each letter to an integer and sums them. Method 1: def digitsum(x): total=0 for letter in str(x): total+=int(letter) return total I thought that this could be improved [...]]]></description>
			<content:encoded><![CDATA[<p>I have a function I wrote for a <a href="http://www.projecteuler.net">project euler</a> that calculates the sum of the digits in a number. This is my first attempt which simply converts each letter to an integer and sums them.</p>
<p><strong>Method 1:</strong></p>
<pre name="code" class="python">
def digitsum(x):
	total=0
	for letter in str(x):
		total+=int(letter)
	return total
</pre>
<p>I thought that this could be improved using ord, which converts a letter into its decimal ascii number. Numbers &#8217;0&#8242;, &#8217;1&#8242;, &#8217;2&#8242; &#8230; &#8217;9&#8242; correspond to the ascii values of 48 &#8211; 57 and then took the moduli of this with 48 to give the integer value. I later realised that this was completely nonsensical and should have just subtracted 48, but I decided to include it for the purposes of the speed test.</p>
<p><strong>Method 2:</strong></p>
<pre name="code" class="python">
def digitsum2(x):
	total=0
	for letter in str(x):
		total+=ord(letter)%48
	return total
</pre>
<p><strong>Method 3:</strong></p>
<pre name="code" class="python">
def digitsum3(x):
	total=0
	for letter in str(x):
		total+=ord(letter)-48
	return total
</pre>
<p><strong>Speed Test:</strong><br />
The test uses a long number and one million repetitions for each method.</p>
<pre name="code" class="python">
from time import time

# .. functions go here

# Nice long number to sum
x=981234153134415646571899783156122451653

tic = time()
for i in range(0,1000000):
	digitsum(x)
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
	digitsum2(x)
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
	digitsum3(x)
print time() - tic, 'Seconds elapsed'
</pre>
<p><strong>Results:</strong></p>
<pre>
#Method 1
29.3496568203 Seconds elapsed
#Method 2
12.185685873 Seconds elapsed
#Method 3
9.59367895126 Seconds elapsed
</pre>
<p>So we can see that the first method is much slower, avoiding the integer conversion by using ord speeds it up the function by ~60% and that using subtraction rather than modulus (a division based operation) saves a further ~20% on top of this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stealthcopter.com/blog/2009/09/python-sum-of-digits-in-a-string/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Python: Checking if a number is prime</title>
		<link>http://www.stealthcopter.com/blog/2009/09/python-checking-if-a-number-is-prime/</link>
		<comments>http://www.stealthcopter.com/blog/2009/09/python-checking-if-a-number-is-prime/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 11:08:30 +0000</pubDate>
		<dc:creator>mat</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://www.stealthcopter.com/blog/?p=78</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of problem solving on Project Euler recently. If your not aware of Project Euler (PE) it is a website with lots of maths / programming based puzzles to solve. Many of the problems involve using or checking prime numbers, in many cases a sieve method would be applicable (see: Sieve [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of problem solving on <a href="http://projecteuler.net/">Project Euler</a> recently. If your not aware of Project Euler (PE) it is a website with lots of maths / programming based puzzles to solve. Many of the problems involve using or checking prime numbers, in many cases a sieve method would be applicable (see: <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a> for a clear explanation / animation). </p>
<p>However sometimes this is not necessary if you only require one prime number, or if memory limitations mean a sieve would be inconceivable. The following is the code I wrote to check if a number is prime or not in python. It tests upwards checking if the number is perfectly divisble, and as it does this it lowers the maximum number need to reach to stop as we know that if a number is not divisible by 2 then it will not be uniquely divisible (a repatition of a divislbe may exist) by anything greater than N/2</p>
<pre name="code" class="python">
def isprime(number):
	if number&lt;=1:
		return 0
	check=2
	maxneeded=number
	while check&lt;maxneeded+1:
		maxneeded=number/check
		if number%check==0:
			return 0
		check+=1
	return 1
</pre>
<p>I hope that this made sense, and is useful to someone. If anyone has any more efficient methods I would be happy to hear from you.</p>
<p>Check out my <a href="http://projecteuler.net/index.php?section=profile&#038;profile=gothicbob">profile</a> to see which problems I&#8217;ve completed. If you&#8217;ve completed any I haven&#8217;t please get in contact and give me some tips.</p>
<p><strong>Update:</strong><br />
<a href="http://www.mikemeat.co.uk">Mike</a> sent a suggestion that I could speed up the program by ignoring all factors of 2, it could also propbably be sped up by looking at 3,4,5 .. etc until certain point.</p>
<pre name="code" class="python">
def isprime(number):
	if number&lt;=1 or number%2==0:
		return 0
	check=3
	maxneeded=number
	while check&lt;maxneeded+1:
		maxneeded=number/check
		if number%check==0:
			return 0
		check+=2
	return 1
</pre>
<p>So lets test the speed difference by doing 1,000 checks of the number 982,451,653 (known to be prime from this useful<a href="http://primes.utm.edu/lists/small/millions/">site</a>)</p>
<p>Original Code:   9.99917411804 Seconds elapsed<br />
Improved Code: 5.2977039814 Seconds elapsed</p>
<p>That&#8217;s approximately a factor of two speed increase, but this makes me think that a combination of the sieve method with this one may lead to an even further increase.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stealthcopter.com/blog/2009/09/python-checking-if-a-number-is-prime/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
