#CJam, <s>46 45</s> 43 bytes ri),{Is___69s_W%erW%=!\6809s-!&IA%g&'.*N}fI I think it can be golfed a little more. Takes `n` from STDIN. [Try it online here][1] [1]: http://cjam.aditsu.net/