magic algorithm