Musicaltypesetting and more

# Calculating the accidental of a note from a key

We will number the pitches of notes as follows (ignoring octaves):

 C D E F G A B $0$ $1$ $2$ $3$ $4$ $5$ $6$

(Major) keys are described by the number of sharps they have, with double sharps counting as $2$, flats as $-1$ etc., that is

 … E♭ B♭ F C G D A E B F♯ C♯ G♯ … … $-3$ $-2$ $-1$ $0$ $1$ $2$ $3$ $4$ $5$ $6$ $7$ $8$ …

Let us first only look at keys where $0$ or more notes are sharps, but not all of them, i.e. from C major to F♯ major ($0\leq k\leq 6$).

$k=0$ has no sharps, and $k=1$ has one at the note F (pitch $3$). Each further key adds a sharp at the next pitch along the circle of fifths, that is the previous added sharp’s pitch $+4$ (fifth $=4$ steps up). In mathematical notation, switching from $k$ to $k+1$ adds a sharp to the notes with pitch $(3+4k\mod 7)=:n_k$.

Since $\gcd(4,7)=1$ this equation can be rewritten as $3+4k\equiv n_k (\text{mod}\ 7) \Leftrightarrow k\equiv (n_k-3) / 4\equiv 2(n_k+4)\equiv 2n_k+1 (\text{mod}\ 7)$. Thus the pitch $n$ has a sharp if and only if the key is $k>k_n:=(2n+1\mod 7)$.

This is for keys $k = 0,\dots,6$. If we pass from $k$ to $k+7$ all pitches receive an extra sharp, resulting in some of them having double sharps; in the same way $k-7$ provides a flat key (all notes flat, some of them raised again to become natural). Therefore the number of “sharps” of pitch $n$ under key $k$ (now all possible keys allowed) is given by $$s(n,k) := \left\lfloor\frac k7\right\rfloor + \begin{cases}1,&(k\mod 7)>k_n\\0,&\text{else}\end{cases}.$$ This formula can be simplified by noting that $-6\leq (k\mod 7)-k_n\leq 6$ and thus $$s(n,k) = \left\lfloor\frac k7\right\rfloor + \left\lceil\frac{(k\mod 7)-k_n}7\right\rceil = \left\lfloor\frac k7\right\rfloor + \left\lceil\frac{k - 7\left\lfloor\frac k7\right\rfloor - k_n}7\right\rceil = \left\lceil\frac{k-k_n}7\right\rceil.$$ So as end result we obtain $$s(n,k) = \left\lceil\frac{k-(2n+1\mod 7)}7\right\rceil.$$