C implementation of the more efficient algorithm
printing the results at the end improves the performance slightly