add magic algorithm and fix bug in reverse algorithm