# CJam, <s>18</s> 17 bytes

    0{sN1$e`2af.b}ri*

*Thanks to @MartinBüttner for golfing off one byte!*

Try it online in the [CJam interpreter][1].

[1]: http://cjam.aditsu.net/#code=0%7BsN1%24e%602af.b%7Dri*&input=10