Optimized math and added memoization to innerloops