[optimization] Replace unnecessary while loops with single equations

Previous code has been simply commented out to make it easier to review and also to make things less complicated in the future if a problem arises from this fix.