Working solution for Problem8