Calculating the number of digits in a series of numbers, experiencing a timeout issue (What is the page count of a book? from codewars)

Solving the Digits in a Book Problem

Find the number of pages in a book based on its summary.

For example, if the input summary is 25, then the output should be n=17. This means that the numbers 1 to 17 have a total of 25 digits: 1234567891011121314151617.

It is guaranteed that all inputs will be valid.

Here is my current solution:

function amountOfPages(summary){

    let n=1;   
    let arrKc=[1]
        
    while((arrKc.join('').toString().length)!=summary){
        arrKc.push( n.toString())
        n++
    }
        
    return n
  
}

All tests are passing successfully, but I am encountering a timeout error when running the function.

https://i.sstatic.net/b1qKf.png

Answer №1

My code snippet:

I have identified a recurring pattern for finding the count of digits, which follows this formula:

9 + 9 * 10^1 * 2 + 9 * 10^2 * 3 + ...+ 9 * 10^(n-1) * n

This solution is based on the above pattern:

function initialLoad() {
      document.getElementById("outcome").innerHTML = "Answer: "+  amountOfPages(25);
}

function amountOfPages(summary) {
        var n = summary;
        var totalNumbersSoFar = 0;
        var pagesSoFar = 0;
        var ninthDigit = "9";
        while (parseInt(ninthDigit) < (n / ninthDigit.length)) {
                var numbersInRange = Math.pow(10, ninthDigit.length - 1) * 9;
                pagesSoFar += numbersInRange * ninthDigit.length;
                n -= numbersInRange;
                totalNumbersSoFar += numbersInRange;
                ninthDigit += "9";
        };
        return ((summary - pagesSoFar) / ninthDigit.length) + totalNumbersSoFar;
    };
 <HTML>
        <HEAD>
        </HEAD>
        <BODY id="outcome" onload="initialLoad()">
            <h1>

        </h1>
        </BODY>
    </HTML>

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

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

Tips for sending data to a server in an object format using the POST method

Could someone kindly assist me? I am attempting to post user data in an object format, but it is not submitting in the desired way. Please, can someone help as I do not want it to create a new object. Here is how I would like it to be submitted: {"birthda ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array? Accessing in Perl: @searchType = $cgi->param('searchType'); print @searchType[0]; Result: employee,admin,users,accounts It appears that the first value in the ...

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...

React: Struggling to retrieve specific elements from an array stored in component state

For a fun side project, I've taken on the challenge of creating a miniature Pokedex app using React. import React, { Component} from 'react'; import './App.css'; import Card from './components/card/Card.component'; clas ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

The styling of divIcons in React Leaflet Material UI is not applied as expected

When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet. Below you can find the code for the project ...

Q-Node - managing an array of Q elements

Having an array of elements like this: var arr = [1, 2, 3, 4, 5, 6, 7, 8], my objective is to apply a specific action to each element sequentially. I don't want these actions to be performed in parallel. For instance: arr.forEach(function(d){ //s ...

Can a custom javascript object be exported in various formats similar to the Date object?

Consider the following scenario where I have a custom object: function MyObject(a, b){ this.prop = a; this.name = b; this.doSomething = function(){ return "something"; } } var a = new MyObject(4, 'name'); I am looking fo ...

Check to see if two words are identical in PHP

Could you please check the word I've written in the text field? If the two words are the same, I should receive a message saying "They are the same." <?php function array_random($arr, $num = 1) { shuffle($arr); $r = array(); for ($i = ...

Error in Laravel 5.5 PusherBroadcaster.php at line 106

I am facing a frustrating issue with the BroadcastException in PusherBroadcaster.php (line 106) error while using Laravel 5.5 and Vue 2.0. Despite trying various solutions, I have been unable to resolve it. Desperately seeking assistance. Here's what ...

ERROR: An issue occurred while attempting to resolve key-value pairs

Within my function, I am attempting to return a set of key-value pairs upon promise completion, but encountering difficulties. const getCartSummary = async(order) => { return new Promise(async(request, resolve) => { try { cons ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

What steps can I take to perform unit testing on a custom element?

While working on a project where I have a class that extends HTMLElement, I came across some interesting information in this discussion: https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089 I discovered that I was unable to create an ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Find all elements with the same class and identify the first element among them using jQuery

In my dynamic data structure, I need to filter out all elements with the class name "My_data" and select the first one. In the code below, I am looking to retrieve the first element with the class "My_data". <div class="all_data"> <div class="lis ...