JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem:

Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times you need to multiply the digits in num until you end up with a single digit.

function persistence(num) {

  let count = 0; 
  let numStr = num.toString(); 

   if (numStr.length === 1){
     return 0
   } 

   if (numStr.length === 2){
     while (numStr.length > 1){
       count += 1
       numStr = (Number(numStr[0])*Number(numStr[1])).toString() 
     }
   }

   if (numStr.length === 3){
     while (numStr.length > 1){
       count += 1
       numStr = (Number(numStr[0])*Number(numStr[1])*Number(numStr[2])).toString() 
     }
   }

   return count 
}

persistence(999) //solution 4

I am facing an issue where I keep getting an "Execution Timed Out (12000 ms)" error. While I understand that there are various approaches to solving this problem, I am particularly interested in understanding what might be incorrect with my code.

Answer №1

The reason why your code is not functioning correctly is due to the continuous addition of str[2] to the final result.

999 > 729 > 126 > 12 > 2

During one loop, you can see that the number becomes 12, causing str[2] to be undefined. As a result, it will lead to NaN, preventing the loop from ending.

A more efficient approach is to use reduce() within a while loop without converting the numbers to Number() while performing multiplication.

function persistence(num) {

  let count = 0; 
  num = String(num);
  while(num.length > 1){
    count++;
    num = String([...num].reduce((ac,a) => a * ac,1));
  }
  return count;
}

console.log(persistence(999))

Answer №2

If you want to achieve this task effortlessly, you can utilize a recursive function:

Simply introduce a new parameter called count (indicating how many times the function has been invoked) and execute the function recursively until the resulting length is greater than 1.

function calculatePersistence(num, count) {
  count = count || 0; 
  let numStr = num.toString(); 
  
  if (numStr.length === 1) {
    return count;
  } 
  let newNum = numStr.split('').reduce((acc, val) => {
    return acc * val;
  }, 1);
  return calculatePersistence(newNum, count + 1);
}

console.log("99", calculatePersistence(99));
console.log("999", calculatePersistence(999));
console.log("99999", calculatePersistence(99999));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

Rotation to a point in a circle using three.js

Currently, I am in possession of 2 instances of THREE.Vector3(). My task at hand is to create a circular shape around one vector with the second vector serving as a tangent. I have determined the radius of the circle geometry based on the distance betwee ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

Embed a React component seamlessly within HTML code

Hey there! I have a situation where I'm pulling valid HTML content from the database and I need to replace merge tags with working React components. The HTML is generated using a WYSIWYG editor. Let me give you an example: const link = <a onClick= ...

What is the significance of the statement "What is the meaning of "#include <common>" in Three.js, WebGL, and GLSL?

The Three.js shader example linked here uses a function called rand() with a vec2 input to create random numbers. Interestingly, the function is not defined within the shader code itself. Instead, it appears to be included through the use of #include < ...

jQuery can be used to mask phone numbers with three input fields

I am looking to implement phone field masking using jQuery or JavaScript. I have tried a few jQuery mask plugins, but I am still searching for a better solution. Specifically, I need three input fields for the USA (it is a requirement). The inputs needed ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

Numerous checkboxes have been chosen alongside a submission button

I recently completed a small project involving multiple checkboxes using ajax. You can view the demo here. However, I am now looking to implement a submit button for filtering options. After selecting multiple checkboxes and clicking the submit button, onl ...

What is the method for defining distinct parameters for nested functions in AngularJS?

When using AngularJS, what happens when a parent function encapsulates a child function that includes parameters not present in the parent? In this scenario illustrated below with the green arrow representing the parent function without any parameters, an ...

The output of VueJs hooks shows a blank refs object first, followed by the referenced elements

Below is the HTML VueJS code sample that I am working with: <div v-for="site in topSites" ref="ts"><a :href="site.url"> ... </div> Update: Here is the full div code: <div v-for="site in topSites& ...

Is there a way to delete a stylesheet if I only have limited information about the url?

I am attempting to dynamically remove a CSS stylesheet using JavaScript or jQuery. I am aware that the target stylesheet is located within the 'head' element and includes the text 'civicrm.css', however, I do not possess the full URL o ...

Using an Ajax request to fetch and display warning information

Exploring the world of MVC and Ajax, I am attempting to generate an Ajax query that will display one of three messages (High risk, Medium Risk, and No Risk) in a div when an integer is inputted. Here's my JSON method: public JsonResult warningsIOPL ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...

Utilize a singular ajax function to handle various events with personalized data parameters

Could someone help me with this specific issue? Here is an explanation. Let's say I have a function called load_window() and various events like clicks, changes, etc. How can I properly create a custom_data variable in these events and use it in the ...

Unable to resolve issue with Display:flex in my CSS, despite numerous attempts

Here is the structure of my CSS and HTML: #TopBar{ display: flex; justify-content: space-between; z-index: 1; position: fixed; top: 0px; left: 0px; background-color: rgb(25,25,25); height:115px; width: 2000px; } #Logo{ top: 0px; height: 110px ...

Learning how to effectively incorporate two matSuffix mat-icons into an input field

I'm currently experiencing an issue where I need to add a cancel icon in the same line as the input field. The cancel icon should only be visible after some input has been entered. image description here Here's the code I've been working on ...