Implemented Problem4
Added a simple check to shorten execution time