/*
* As discussed on StackOverflow
* http://stackoverflow.com/questions/19434497/an-algorithm-to-find-the-seed-root-of-a-given-number/19439893#19439893
*/
#include<iostream>
using namespace std;
typedef long long int Big_Int;
void root_stem(const Big_Int r, const Big_Int product_of_my_digits, const Big_Int target) {
// There are two rules we can use to prune:
//
// First: The product_of_my_digits must divide into the target.
// If not, return
// Second: The products produced lower in the search true will always be higher
// than those above. Therefore, we should return early if
// my_seed_product is larger than the target
if (target % product_of_my_digits != 0)
return;
Big_Int my_seed_product = r * product_of_my_digits;
if(my_seed_product >= target) {
if (my_seed_product == target) {
cout << r << "\t->\t" << my_seed_product << endl;
}
return;
}
// print all roots, with their products, between 10*r and 10*r + 9
for(Big_Int digit_to_append = 1; digit_to_append<=9; ++digit_to_append) {
root_stem(r*10 + digit_to_append, product_of_my_digits*digit_to_append, target);
}
}
int main() {
root_stem(0,1, 4977);
root_stem(0,1, 24562368);
root_stem(0,1, 176852740608);
return 0;
}
LyoKICogQXMgZGlzY3Vzc2VkIG9uIFN0YWNrT3ZlcmZsb3cKICogaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy8xOTQzNDQ5Ny9hbi1hbGdvcml0aG0tdG8tZmluZC10aGUtc2VlZC1yb290LW9mLWEtZ2l2ZW4tbnVtYmVyLzE5NDM5ODkzIzE5NDM5ODkzCiAqLwoKI2luY2x1ZGU8aW9zdHJlYW0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp0eXBlZGVmIGxvbmcgbG9uZyBpbnQgQmlnX0ludDsKCnZvaWQgcm9vdF9zdGVtKGNvbnN0IEJpZ19JbnQgciwgY29uc3QgQmlnX0ludCBwcm9kdWN0X29mX215X2RpZ2l0cywgY29uc3QgQmlnX0ludCB0YXJnZXQpIHsKCiAgICAgICAgLy8gVGhlcmUgYXJlIHR3byBydWxlcyB3ZSBjYW4gdXNlIHRvIHBydW5lOgogICAgICAgIC8vCiAgICAgICAgLy8gRmlyc3Q6IFRoZSBwcm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