algorithm implemented with java