Magical algorithm