L'algoritmo che mi hai mandato è giusto, peccato che sia VB
mentre io sto programmando in JAVA.