I'm stuck on finding the solution for PROJECT EULER P4

Challenge 4

Palindrome numbers read the same forwards and backwards. The largest palindrome that can be formed by multiplying two 3-digit numbers is 9009 = 91 × 99. Your task is to find the largest palindrome made from the product of two 3-digit numbers.

I'm sharing my code below. It successfully finds the largest palindrome for 2-digit numbers, which is 9009. However, when I run the code for 3-digit numbers, the correct answer is 906609 while I'm getting 956459. I can't figure out what's wrong with my code, can someone please help me? Thanks.

let result;//product of two numbers
let palindromes=[];//array for palindrome numbers
for(i=100;i<1000;i++)
{
    for (j=100;j<1000;j++)
    {
        result = i*j;
        str= result.toString();//change the number to a string
        if (str.substr(0,1) == str.substr(-1,1) && str.substr(1,1) == str.substr(-2,1))
        {
            palindromes.push(result);
        }
        else{};
    };

};
console.log(palindromes);
console.log(Math.max(...palindromes));

Answer №1

By making the following modification, I was able to arrive at the correct answer.

for(i=100;i<1000;i++) {
    for (j=100;j<1000;j++){
        num = i*j;
        str= num.toString();//convert the number to a string
        let len = str.length - 1;
        let checkedDigit = [];

        //Iterate through the string from 0 to half the string length to check for palindromes.
        for (k = 0; k < str.length/2; k++) {
            if (str.substr(k, 1) === str.substr(len - (len + 1 + k), 1)) {
                //If the corresponding digits are equal, mark as true. (Otherwise, mark as false)
                checkedDigit[k] = true;
            } else {
                checkedDigit[k] = false;
            }
        }

  function checkDigit(val) {
    return val === true;
  }

  //Check if all elements in checkedDigit array are true.
  if (checkedDigit.every(checkDigit)) {
    paNum.push(num);
  }

};
};
console.log(paNum);
console.log(Math.max(...paNum));

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

Utilize JavaScript to iterate through a JSON object and retrieve the indices that meet the specified criteria

While I found a previous answer that somewhat addresses my issue, I am seeking guidance on how to return an array of the indexes where a specific value appears. For example, if **18A38** is the target value, it should return the positions [1,3]. The sampl ...

Deciphering the meaning of the 'this' keyword in a prototype function of an object

var Controller = function () { try { throw new this.userException('test', 'test'); } catch (error) { if (error instanceof this.userException) { console.error(error.stack); } } } Controller.prototype.userExceptio ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

Using JavaScript, learn how to extract query parameters and encoded information from a URI

I am looking for a specific module in order to extract information from query parameters within a URL. The format includes 2 query parameters and an encoded piece of data. Do I need to use split functions or is there a more direct approach available? Sampl ...

Automatically press a button that appears on the webpage

I am looking to automate the clicking of a button that appears on a website. How can I accomplish this using Python? I have no experience in JavaScript and am fairly new to programming. Here is the outer HTML code for the button: <button type="button" ...

Tips for utilizing pre-installed validation regulations in VeeValidate 4?

Currently transitioning from Vue 2 to Vue 3, I am interested in utilizing VeeValidate 4 for my validations. However, it seems that the documentation does not provide any information on using built-in rules such as min, max, alpha_spaces, etc. Do I need to ...

Is it possible to make a div jump or bounce if it has a flex display?

I'm looking to add some interactive animation to an image inside a div when my mouse hovers over it. To better explain the issue I'm facing, I created a quick representation of what I want to achieve in the code below. My goal is to have the te ...

Encountering issues with verifying login credentials in Angular 2

Greetings! I have designed a login page where the user will be logged in if the response is successful, otherwise an error message will be displayed. Below is the JSON data with email and password fields: { Email": "<a href="/cdn-cgi/l/email-protect ...

What is the best way to retrieve a URL from a function in an HTML/JavaScript environment?

Recently, I delved into learning HTML and JavaScript. One of the challenges I encountered is figuring out how to access a URL or download a file from a function written in JavaScript that was imported from another file using: <script src="jscriptSheet. ...

What is the most effective method in React JS to achieve real-time results with every keystroke by making REST calls to the server?

We are dealing with a huge database and the task at hand is to display results as the user types them in the search box. Preloading queries to attempt matching is out of question due to the enormity of our data. Currently, we make a server request with th ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Tips for displaying a specific PDF file using the selected programming language

As a newcomer to react.js, I have a question regarding my system which allows the user to select the default language. If the chosen language is French, there is a specific URL that needs to be included in the Iframe path. For Spanish, it's a specific ...

Modifying the data attribute within the div does not result in a different image for the 360-degree spin view

My current project involves utilizing js-cloudimage-360-view.min.js to create a 360-degree view of images. I have successfully retrieved the images, but I am encountering difficulty in updating the images by clicking a button. index.html <!DOCTYPE html ...

Can anyone point me in the direction of the source code for JSON.parse in Node.js, JavaScript, or V8?

When using JSON.parse(fileName_or_stringOfJSON), the string is converted into an object. I'm curious about how this conversion process works in NODEJs and where the source code can be found. ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Is there a way to trigger another API call when clicking a button in Vue.js?

I recently started using vue js and I am facing a challenge with this component. I am attempting to trigger another API call when one of the list options is clicked. <template> <div> <h1 class="text-center text-4xl font-bold">Our ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Error message: JavaScript multiline strings within backticks are currently unsupported in Internet Explorer

My HTML string, stored in a variable, is being used to populate the innerHTML. Although the first example (using backtick syntax) is simple, it does not function in Internet Explorer 11. Is there a way to make the first example work in Internet ...

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...

Tips for preventing JavaScript errors when making cross-domain requests using AJAX

Is there a way to prevent or handle JavaScript errors without causing the script to crash? Error message: No data returned $.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=dsfsdfsd&country= ...