#Pyth, 22 bytes

    ivMeSs.:RQ.n,L_MdCB.zT

If we are allowed to print leading zeroes, the code is 18 bytes:

    eSs.:RQ.n,L_MdCB.z