Skip to content

Instantly share code, notes, and snippets.

@vankasteelj
Created July 24, 2016 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vankasteelj/b6b0b30a57a46a925d8ea3b4472581b7 to your computer and use it in GitHub Desktop.
Save vankasteelj/b6b0b30a57a46a925d8ea3b4472581b7 to your computer and use it in GitHub Desktop.
find the multiplicative persistence of a number
// EN:calculate a given number's multiplicative persistence
// FR:calculer la persistance multiplicative d'un nombre donné
// Start number | nombre de départ
var n = 277777788888899;
var y = n;
var pst = 0;
while (y >= 10 && isFinite(y)) {
var z = 1;
var x = y.toString();
for (var i in x) {
if (typeof x[i] != "function") {
z *= x[i];
}
}
console.log(z);
y = z;
pst++;
}
console.log('%d: %d', n,pst);
@vankasteelj
Copy link
Author

vankasteelj commented Jul 24, 2016


// function to check numbers, starting from NUMBER, trying to find a persistence of PERSISTENCE
function count(NUMBER,PERSISTENCE) {
    // start checking at ?
    var n = NUMBER;

    // Find a persistence of ?
    var lookingFor = PERSISTENCE;

    // Required variables
    var pst = 0; // initialize persistence counter
    var x, y, z;
    var total = 0;

    // keep looping if given persistence wasn't found or if we did a million iteration
    while (pst < lookingFor && total < 1000000) {
        y = n;

        // ignore numbers with a zero/null in them
        if (y.toString().indexOf(0) === -1) {
            console.log('counting...');

            // reset persistence counter for new number
            pst = 0;

            // keep looping if the number isn't a single digit
            while (y >= 10 && isFinite(y)) {

                // reset the total count to 1 (to multiply it with each digit)
                z = 1;

                // use number as a string to isolate each digit
                x = y.toString();

                // multiply each digit with the others from within the number
                for (var i in x) {
                    if (typeof x[i] != 'function') {
                        z *= x[i];
                    }
                }

                y = z;
                pst++;
            }

        }

        // prepare next iteration
        n++;
        total++;
    }

    // give results
    if (pst < lookingFor) {
        console.log('Not found. Last checked number was %d', n - 1);
    } else {
        console.log('Found: %d persistence is %d', n - 1, pst);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment