http://rosettacode.org/wiki/Knuth's_algorithm_S