Sub-string Divisibility
The number, , is a to pandigital number because it is made up of each of the digits to in some order, but it also has a rather interesting sub-string divisibility property.
Let be the st digit, be the nd digit, and so on. In this way, we note the following:
- is divisible by
- is divisible by
- is divisible by
- is divisible by
- is divisible by
- is divisible by
- is divisible by
Find the sum of all to pandigital numbers with this property.
Implementations
#include <iostream>#include <string>#include <algorithm>#include <vector>
long long substring_divisibility() { std::string digits = "0123456789"; std::sort(digits.begin(), digits.end()); std::vector<int> primes = {2, 3, 5, 7, 11, 13, 17}; long long sum = 0; do { bool valid = true; for (int i = 0; i < 7; i++) { int num = std::stoi(digits.substr(i + 1, 3)); if (num % primes[i] != 0) { valid = false; break; } } if (valid) { sum += std::stoll(digits); } } while (std::next_permutation(digits.begin(), digits.end())); return sum;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << substring_divisibility() << std::endl;}#endif // UNITTEST_MODESolution Notes
Mathematical Background
A pandigital number uses each digit from 0 to 9 exactly once. The problem requires finding all such numbers where specific 3-digit substrings are divisible by given primes.
The substrings and their divisors are:
- d₂d₃d₄ divisible by 2
- d₃d₄d₅ divisible by 3
- d₄d₅d₆ divisible by 5
- d₅d₆d₇ divisible by 7
- d₆d₇d₈ divisible by 11
- d₇d₈d₉ divisible by 13
- d₈d₉d₁₀ divisible by 17
Algorithm Analysis
The solution generates all permutations of digits 0-9 and checks each against the divisibility conditions. Since 10! = 3,628,800 permutations, brute force is feasible.
For each permutation, convert to string and check seven 3-digit numbers for divisibility. Early termination in some implementations (like backtracking in JavaScript) prunes invalid branches.
Performance Analysis
- Time Complexity: O(10! × 7) ≈ 25 million operations, very fast on modern hardware
- Space Complexity: O(1) for most implementations, O(10!) for storing all permutations in some
- Execution Time: <1 second typically
- Scalability: Fixed at 10 digits, no scaling concerns
Key Insights
-
Divisibility by 2 and 5 can be checked by last digit
-
Divisibility by 3 and 9 by digit sum
-
Higher primes require full number checking
-
Backtracking reduces permutations significantly
-
No leading zero constraint for the number itself
Educational Value
This problem demonstrates:
-
Permutation generation algorithms
-
Modular arithmetic and divisibility rules
-
Backtracking optimization techniques
-
Performance trade-offs between memory and computation
-
The intersection of combinatorics and number theory