improved implementation of multinomial