basic algorithm implemented in Java and Python