Partial solution for Prometheus 2014 contest - http://www.codechef.com/PRMT2014/