First we note a few things about a cyclic group $G$ of order $n$:
- There is an element in $G$ of order $k$ iff $k\mid n$.
- Taking an element $b\in G$ of order $k$, all other elements of $G$ of order $k$ are contained in $\langle b \rangle$.
From this, we may conclude that we need only to focus on the number of elements of order $n$. Why? Because for any other order $k$, either $k \nmid n$ and there are zero elements of that order, or $k \mid n$, and there is an element $b$ of order $k$, and we can just look at the group $\langle b \rangle$.
Finally, given your $a \in G$ as a generator for the group, what is the criterion that $a^m$ is a generator for $G$, i.e. that $O(a^m) = n$? Going by your formula, that would be when $\gcd(m, n) = 1$. How many such numbers are there? Fortunately, that's a question that's been pondered before, and the answer is called $\phi(n)$.
(This means that if you have some $k\mid n$ instead, you get the answer by applying the above to the group $\langle b\rangle$, which gives $\phi(k)$.)