Solving prime ring problem in java