UVA11461 implementation in java