Completed SRM 587.cpp