Add code and testcases of problem 583