Problem 9

completed November 30, 2011

Try One

Comments

I was hoping I could just do this by brute force, that is, to test every integer in every combination for a, b, and c. But it will take roughly 40 minutes to arrive at the answer with this method.

Code

set t to (time of (current date))
set a to 1
set b to 1
set c to 1

repeat
	repeat
		repeat
			if ((a ^ 2 + b ^ 2) = (c ^ 2)) and (a + b + c = 1000) then
				log ((time of (current date)) - t)
				return {a, b, c, (a * b * c)}
			end if
			set a to a + 1
		end repeat
		set b to b + 1
	end repeat
	set c to c + 1
end repeat

Try Two

Resources

I used wikipedia to give me the formula for deriving all Pythagorean triples using the variables k, m, n.

Comments

I was shocked when this code took only 1 sec to complete.

Code

set t to (time of (current date))
set k to 1
set m to 1
set n to 1

repeat until n = 1000
	repeat until m = 1000
		repeat until k = 1000
			log {k, m, n}
			set a to (k * (m ^ 2 - n ^ 2))
			set b to (2 * k * m * n)
			set c to (k * (m ^ 2 + n ^ 2))
			if (a + b + c = 1000) and (a is not 0) and (b is not 0) then
				log ((time of (current date)) - t)
				return {a, b, c, a * b * c}
			end if
			set k to k + 1
		end repeat
		set k to 1
		set m to m + 1
	end repeat
	set m to 1
	set n to n + 1
end repeat