Second algorithm