TITLE: How many integers between $1$ and $10^n$ contain $14$?
QUESTION [7 upvotes]: How can we derive a formula to calculate the number of integers between $1$ and $10^n$ that contain the number $14$ (as a string)?
For example, there are $20$ integers from $1$ to $1000$ that contain at least one $14$:

"14","114","140","141","142","143","144","145","146","147","148","149","214","314","414","514","614","714","814","914"

REPLY [3 votes]: This is a variant on Rebecca Stone's answer.  Let $G(n)$ count the number of "good" length-$n$ strings that contain a $14$, and let $B(n)$ count the number of "bad" strings that don't.  Clearly
$$G(n)+B(n)=10^n$$
You can create a bad string of length $n$ by appending any digit you want to a bad string of length $n-1$, unless the shorter string ends in a $1$, in which case you can't append a $4$.  The number of such strings (ending in a $1$) is $B(n-2)$.  Thus
$$B(n)=10B(n-1)-B(n-2)$$
with starting values $B(1)=10$ and $B(2)=99$.  This gives the the "bad" sequence
$$10, 99, 980, 9701, 96030, 950599, 9409960, 93149001,\ldots$$
which is A004189 in the OEIS, where it's noted that
$$B(n)={(5+\sqrt{24})^{n+1}-(5-\sqrt{24})^{n+1}\over2\sqrt{24}}$$
Thus
$$G(n)=10^n-{(5+\sqrt{24})^{n+1}\over2\sqrt{24}}+{(5-\sqrt{24})^{n+1}\over2\sqrt{24}}$$
as robjohn found.