"use strict";/**
* Compute the multiplicative persistence of a number.
*
* @param {number} number The number to compute the persistence from.
*
* @throws {Error} If the function is called with not exactly one argument.
* @throws {TypeError} If the first argument is not an integer.
* @throws {RangeError} If the first argument is not greater than or equal to zero.
*
* @return {number} The persistence of the number.
*
* @example
* persistence(39); // 3
* persistence(999); // 4
* persistence(4); // 0
*/constpersistence=(number:number,...extraParameters:unknown[]):number=>{if(0!==extraParameters.length){thrownewRangeError("The function has not been called with exactly one argument.");}if(!Number.isInteger(number)){thrownewTypeError("First argument is not an integer.");}if(0>number){thrownewRangeError("First argument is not greater than or equal to zero");}constcharacters=number.toString();if(1===characters.length){return0;}return1+persistence([...characters].reduce((total,character)=>total*parseInt(character),1));};
/*
Recursion :
persistence(num) = 0 if num < 10
= [1 + persistence(multiplication of digits of num)] if num >= 10
*/intpersistence(intnum){// Given number is positive, so no need to check for negative numbers// if number is already single digit return 0if(num<10)return0;// get the multiplication of digitsintmul=1;while(num>0){mul*=(num%10);num/=10;}// return 1 + persistence(mul)return1+persistence(mul);}
fromfunctoolsimportreducedefpersistence(n):count=0whileTrue:iflen(str(n))==1:returncountn=reduce(lambdax,y:x*y,[int(i)foriinstr(n)],1)count+=1if__name__=="__main__":test_cases=[39,999,4,5,52,377]expected_results=[3,4,0,0,2,4]total_test_cases=len(test_cases)foriinrange(total_test_cases):test_case=test_cases[i]expected_result=expected_results[i]result=persistence(test_case)assert_message="persistence({}) returns {}. Expected {}".format(test_case,result,expected_result)assertresult==expected_result,assert_messageprint("Passed all {} test cases".format(total_test_cases))
Haskell solution:
Edit:
Inspired by other solutions I realized that I don't need to track recursion depth
Nice use of pointfree style!
Python solution
My Swift solution :
TypeScript
Nice 👌
Elixir
C++ solution
Python solution with test cases.
JS
JS solution