Wednesday, January 19, 2011

Problem 4 - Palindromic Numbers

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.

My first attempt at this is pretty straightforward brute-force code:
Start with 999 * 999 and iterate downward (999 * 998, 999* 997, 999 * 996 ... 999 * 1, 998 *999, 998 * 998) It's even less efficient than 999-squared since it doesn't remember that multiplication is reversible, so it would do both 999 * 998 and 998 * 999.

The algorithm coverts the digits into a string, then does a comparison w/ the reverse of the string, and if they match, adds them to a List. I only do 10,000 checks since my assumption was that the winning number, being the highest sum of digits, it would have to have a lot of 9's in it, probably beginning and ending w/ a 9.



(
var p=(List());
100.do({|j|
100.do({|i|
var n =((999-j) * (999-i)).asString,c=0,s;
(n.reverse==n).if ({
p.add([999-j,999-i,n.asInt]);
});
});
});
p.sortBy(2).reverse;
)


I save both multiples that product the number, along with the product, then use sortBy to sort the resulting array by the 2nd key.

This is the first sonification I've done for Project Euler so far that I've really liked - here's the code + a recording of the first one. I'll post more details in a later post.

(
Routine{
500.do({|j|
j.postln;
999.do({|i|
var n =((999-j) * (999-i)).asString,c=0,s;
(n.reverse==n).if ({
Routine {
n.size.do({|k|
var s,freq;
s = Synth("sine");
freq = (n.at(k).digit +1) *(4096 / (2**i.log.ceil));
s.set(\freq,freq ,\atk,0.001,\rel,((i+3).log + (j+3).log),\pan,(j/1000)* (-1**i) *2/3,\amp,0.3 * (1/(freq+128)),\sus,-32,\gate,1);
(1/ 8).wait;
});
}.play;
});
(1/1024).wait;
});
});
}.play;
)

4.2 by Backtrace

No comments:

Post a Comment