HeNeos blog

Josue H. @ JP Morgan Chase

HeNeos

← Back to all posts

Project Euler 043

March 26, 2023

#project-euler#algorithms#number-theory

Sub-string divisibility

First, try with all multiples of 17 that has different digits:

cba‾≡mod  17\overline{cba} \equiv \mod 17

Since aa, bb and cc are known values, the next step is:

dcb‾≡mod  13\overline{dcb} \equiv \mod 13

to calculate the value of dd:

100d+10c+b≡0mod  13100d + 10c + b \equiv 0 \mod 13 d≡−(10c+b)inv(100,13)mod  13d \equiv -(10c+b)\text{inv}(100,13) \mod 13

More generally:

100z+10y+x≡0mod  p100z + 10y + x \equiv 0 \mod p z≡−(10y+x)inv(100,p)mod  pz \equiv -(10y+x)\text{inv}(100, p) \mod p

Since xx and yy are known values, −(10y+x)%p-(10y+x)\%p is also known. To calculate inv(100,p)\text{inv}(100, p) is enough with a preprocessing for every prime number from 22 to 1717. Finally, the equation is similar to: z≡kmod  pz \equiv k \mod p, so for every digit the search space is reduced for just 11 or 22 values.

Time Complexity: O(20×10×10)O(20\times 10\times 10)

Just for 22 and 55 is needed to iterate from 00 to 99 and there are just 2020 numbers that met the requirements for 1717.