Solved problem 4 in Java.