Discovering the highest prime factor of a number using Javascript

My current focus is on creating a basic program in JavaScript that can identify the largest prime factor of an integer. Here is the code I have developed for this purpose:

let result;

function findFactor(number, half) {
    for (let i = 2; i < half; i++) {
        if (number % i == 0) {
            result = number / i;
            findFactor(result, result / 2);
        }
    }
}

findFactor(30, 15);
console.log(result);

While the efficiency and accuracy of this code remains uncertain, there is a specific issue that has grabbed my attention: After the i = 2 step within the findFactor function, I noticed that the values of number = 5, half = 2.5, and result = 5. However, without any explicit instruction in the code to make changes, the values suddenly revert back to 15 and 7.5. This unexpected behavior requires further investigation.

Answer №1

The function is being called recursively, and each time it's called, a new set of variables for target, half, and i is created. For instance, in the initial call to factor, target is 30 and half is 15. When the function is called again with arguments 15 and 7.5, the inner call gets its own sets of target (15) and half (7.5), while the outer call retains its copies of target (30) and half (15). This pattern continues with subsequent recursive calls to factor, creating distinct sets of variables each time. As you return from the innermost call, its variables are cleared out, revealing the values from the calling context.

To illustrate this concept more simply, consider the following example:

function countdown(value, indent) {
    var twice = value * 2;
    console.log(indent + "[before] value = " + value + ", twice = " + twice);
    if (value > 0) {
        countdown(value - 1, indent + "  ");
    }
    console.log(indent + "[after]  value = " + value + ", twice = " + twice);
}
countdown(3, "");
.as-console-wrapper {
    max-height: 100% !important;
}

The output generated by this code snippet is as follows:

[before] value = 3, twice = 6
  [before] value = 2, twice = 4
    [before] value = 1, twice = 2
      [before] value = 0, twice = 0
      [after]  value = 0, twice = 0
    [after]  value = 1, twice = 2
  [after]  value = 2, twice = 4
[after]  value = 3, twice = 6

This output demonstrates that changes made in an inner call do not affect variables in the outer scope; each invocation creates its own separate set of variables.

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

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

"Is it possible to make a JSON API call in Node.js before exiting with a SIGINT

In my attempt to configure certain variables and make an API call using the request module before exiting the program, I encountered issues where the function was not being properly executed due to the presence of both SIGINT and exit signals: const reque ...

The error "Property 'user' does not exist on type 'Session'." occurred while attempting to pass session data using express-session and accessing req.session.user

I'm currently working on creating a basic login form for users to access a website, where I plan to store their session data in a session cookie. The express-session documentation provides the following example for setting it up: app.post('/login ...

What are the steps to resolve the issue of "npm ERR! EEXIST: file already exists, rename" occurring with non-existent files?

Welcome to my first question post. (Please be kind if I make mistakes.) I am using node version 5.6.0. For an assignment, I downloaded a JS web app but am encountering an error that is preventing me from working on it: S:\PersonalCloud\jennyly ...

Updating JSON data within JavaScript

Currently, I am in the process of developing a webpage that pulls data from a json feed. However, I am looking to have it update every 30 seconds without refreshing the entire page, just refreshing the Div & Jquery elements. I have attempted various solut ...

What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and ...

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...

What is the purpose of using Array.prototype.slice.call(nodeList) for handling DOM elements?

Many JavaScript libraries like jQuery and Zepto frequently use Array.prototype.slice.call on querySelectorAll(), getElementsByTag, or ClassName results. Despite browsing numerous questions and answers on StackOverflow about this topic, I understand that it ...

Transferring streaming data from Node.js to an ElasticSearch database

Currently, my Node.js script is extracting data from a large USPTO Patent XML file (approximately 100mb) to create a patentGrant object. This object includes details such as publication number, country, date, and type of patent. I am working on storing a ...

Position divs to be perfectly aligned and centered

I'm in the process of creating a webpage and facing challenges with aligning my divs properly, specifically the animated company logos. I want them to be positioned side by side rather than on top of each other, with space in between to fit the layou ...

Searching for a method to execute actions prior to the "enter" event in ng-animate, similar to the beforeAddClass function

//trying to replicate the top animation with the enter-leave animation below app.animation('.answer-animation', function(){ return { beforeAddClass: function(element, className, done){ if (className == 'answer') { ...

Is there a way to convert my function into a variable in order to execute an array of statements

I'm struggling to convert this code into a variable. I need to bind it inside a statement execute array. This is the code I am working on, which retrieves the current date and timezone. I attempted using $date = function() {}, echo $date(); but that ...

What is the best method for retrieving values from a FlexiGrid?

I'm having trouble finding information on how to retrieve a cell's value from a flexigrid. My goal is to fetch the value of the third column for every checked item (each row has a checkbox). While I have a function that successfully gets the ro ...

There seems to be an issue with the Url.Action method as it

I'm working with this script: $(function() { $.support.cors = true; jQuery.support.cors = true; $.ajax({ crossDomain: true, type: 'GET', url: 'http://example.com/WCFRESTService.svc/GetCategories&apos ...

Solving SEO issues with jQuery load()

I have developed a modal window that includes links, but unfortunately, search engine crawlers are unable to read and index those links. I am looking for a solution to make sure the crawler can index those links. I have noticed websites using AngularJS li ...

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

Continuous Load More: Loads content infinitely until a page is fully loaded

I am currently experimenting with implementing infinite ajax scroll within a Bootstrap modal. Below is the initial appearance of the modal, before any data is loaded: <div class="modal fade" id="modal" tabindex="-1"> <div class="modal-dialog" ...

The event fails to propagate up to the parent component

I have a project structure set up as follows: https://i.stack.imgur.com/bvmK5.jpg The todo-form component triggers the created event and I am looking to handle this event in the todos component. todo-form.component.html: <form class="todo-form" ( ...

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...