Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Multiplicative Persistence (JavaScript)
    Not sure why my code doesn't work. Any help is appreciated! Question: Using the JavaScript language, have the function MultiplicativePersistence(num) take the num parameter being passed which will always be a positive integer and return its multiplicative persistence which is the number of times you must multiply the digits in num until you reach a single digit. For example: if num is 39 then your program should return 3 because 3 * 9 = 27 then 2 * 7 = 14 and finally 1 * 4 = 4 and you stop at 4.
    var count = 0;
    function MultiplicativePersistence(num) { 
      if(num.toString().length == 1){
        return count;
      }
      count ++; 
      var mult = 1;
      var splitStr = num.toString().split("");
      for(var i = 0; i<splitStr; i++) {
        mult *= parseFloat(splitStr[i]);
      }
      return MultiplicativePersistence(parseFloat(mult));        
    }
    
    yinjia posted this question on 11/3/15 | javascript, multiplicative
    Answers
  • +
  • 1
  • -
  • You forgot add .length on line 9.
  • +
  • 0
  • -
  • Add .length on line no 9 after splitStr the revised code would be as follows
    var count = 0;
    function MultiplicativePersistence(num) { 
      if(num.toString().length == 1){
        return count;
      }
      count ++; 
      var mult = 1;
      var splitStr = num.toString().split("");
      for(var i = 0; i<splitStr.length; i++) {
        mult *= parseFloat(splitStr[i]);
      }
      return MultiplicativePersistence(parseFloat(mult));        
    }
    
    Log in to write an answer.