My code is not optimized so it cross the time limit. Is there any math like way to solve this problem?