Solved problem3 in java (faster solution)