help in optimizing solution of a spoj problem.

prob : http://www.spoj.com/problems/COOLNUMS/

my soln : https://ideone.com/qw9NDK

It is giving TLE please help!