This builds directly on factorization: divide out the small factors and remember the last one. Whatever is left above 1 at the end is the largest prime factor.
Because you divide n down as you go, the loop bound d × d ≤ n keeps shrinking. That makes the algorithm fast even for numbers near 10¹² when they have small factors.