If a number contains two repeating sequences of digits, then it must be of the form aa where a is the repeating sequence; written another way, the number is a⋅10d+a=a⋅(10d+1) where d is the number of digits in a, which is ⌊log10a⌋+1. These numbers form the set {a⋅(10d(a)+1)∣a≥1}.
The search ranges only contain fewer than 2,000,000 numbers, so it's possible to brute-force each number and check its inclusion in this set. However, for each range [L,R], we can actually find its intersection with the set above in constant time by finding the smallest and largest a, since a⋅(10d(a)+1) is a monotonous, piecewise linear function. We just need to solve the inequalities
a1⋅(10d(a1)+1)a2⋅(10d(a2)+1)≥L≤R
To solve the first one, we can first determine the value of d(a1). For each value of d(a1), a1 is in the range [10d−1,10d−1]. So the smallest d needs to satisfy (10d−1)⋅(10d+1)≥L.
Now we have the range of d values. For each d, we can get all valid a values [al,ar] which is the intersection of [10d−1,10d−1] and [⌈L/(10d+1)⌉,⌊R/(10d+1)⌋]. The sum of them is (10d+1)⋅∑a=alara=(10d+1)⋅2(al+ar)(ar−al+1).
let d_min =((*low asf64+1.0).log10()/2.0).ceil()asu32; let d_max =(((40**high +1)asf64).sqrt()/2.0-0.5).log10().floor()asu32; for d in d_min..=d_max { let multiplier =10u64.pow(d)+1; let a_min =ceil_div(*low, multiplier).max(10u64.pow(d -1)); let a_max =(*high / multiplier).min(10u64.pow(d)-1); if a_min > a_max { continue; } total +=(a_max - a_min +1)*(a_max + a_min)* multiplier /2; }
Now the number can contain any number of repeating sequences of digits, so it can be any of aa, aaa, aaaa, etc.
I'm sure there's still a closed-form solution, but I don't see it right now. There's a second complication, which is double-counting: for example, 222222 can be counted as 22 * 10101, or 222 * 1001. To avoid this, I have to enumerate every number in the ranges and check if it has repeating sequences. I hardcoded each value of the multiplier and the corresponding range of a values: