New algorithm for task3