Working solution for Problem5