speeding up algorithm