Solution using tail-recursion.