Determine if integer contains another integer

280 Views Asked by At

Is there a numeric method one can use to determine if a non-negative integer contains another non-negative integer?

For example, the integer 1472 contains 47. (Any number A that is a substring of another number B would be contained by B.)

My specific application is for substring matching within an OpenGL shader, but that shouldn't matter.

I can imagine some algorithmic approaches to this problem, and feel like there could be some clever modulo-related approach to determine if a number contains another number. That said, I haven't cracked this yet.

Any suggestions or hints others can offer would be hugely appreciated! If this question belongs elsewhere please just let me know and I'll move it...

1

There are 1 best solutions below

0
On

Can't think of a clever way, so I'll try brute force.

For any positive integer $n$, let $nd(n)$ be the number of digits in $n$ so $nd(n) =\lfloor \log_{10}(n) \rfloor + 1$.

To see if $n$ is a part of $m$, check if

$10^{nd(n)}\lfloor \dfrac{m}{10^{k+nd(n)}} \rfloor =\lfloor \dfrac{m}{10^{k}} \rfloor-n $ for $k = 0 $ to $nd(m)-nd(n)-1$.

The left side is $m$ with the right $k+nd(n)$ digits deleted and then shifted left $nd(n)$ digits.

The right side shifts $m$ right $k$ digits and subtracts $n$.

If the two are the same, the right $nd(n)$ digits of $m$ shifted right $k$ digits match $n$.

If they are never the same, $n$ never matches $m$.