The problem of designing an optimal weighted voting system for the two-tier voting, applicable in the case of the Council of Ministers of the European Union (EU), is investigated. Various arguments in favour of the square root voting system, where the voting weights of member states are proportional to the square root of their population are discussed and a link between this solution and the random walk in the one-dimensional lattice is established. It is known that the voting power of every member state is approximately equal to its voting weight, if the threshold q for the qualified majority in the voting body is optimally chosen. We analyze the square root voting system for a generic union of M states and derive in this case an explicit approximate formula for the level of the optimal threshold: q simeq 1/2+1/sqrt{{pi} M}. The prefactor 1/sqrt{{pi}} appears here as a result of averaging over the ensemble of unions with random populations.