How to calculate the occurrence of a stretch of nucleotides in a genome?
Strictly speaking the question is from the realm of probability theory. If the probability of a nucleotide $X$ in the genome is $p_X$ ($\sum_x p_X=1$), then the probability to encounter a particular sequence, where nucleotide $X$ occurs $n_X$ times, is
$$
\prod_X p_X^{n_X} = p_A^{n_A}p_C^{n_C}p_G^{n_G}p_T^{n_T}.
$$
The formula given in the question is a particular case for $p_C=p_G=g/2$, $p_A=p_T=(1-g)/2$,
$$
\left(\frac{g}{2}\right)^{n_C+n_G}\left(\frac{1-g}{2}\right)^{n_A + n_T}
$$
which is obviously always the case for DNA, where the numbers of Cs and Gs (or As and Ts) are always the same, but the more general formula could serve for RNA or proteins.
What one should keep in mind is that the formula above is for a sequence with a particular order of the nucleotides! If the order is immaterial, and only the content of the sequence matters, the formula has to be multiplied by a binomial factor, which is effectively summing over all the possible arrangements of the nucleotides. Thus, for the case of DNA we obtain
$$
{n_A + n_C + n_G + n_T \choose n_C + n_G} 
\left(\frac{g}{2}\right)^{n_C+n_G}\left(\frac{1-g}{2}\right)^{n_A + n_T}
$$
You can check yourself that the difference due to the binomial factor is striking!