What could be causing the prime factorization function to malfunction?

I have encountered an issue with a simple JavaScript function I created to factor down numbers into primes. The problem arises when the input number is the product of duplicate prime numbers, as the function does not include these duplicates in the array of factors. Let's take the number 28 as an example. 28 can be expressed as 2 * 2 * 7 = 2^2 * 7. When I run my function factor(n) with n = 28, I expect the result to be [2, 2, 7]. However, the current output is only [2, 7]. Can anyone assist me with fixing this problem? Below is the code for the function in JavaScript:

function factor(n) {
  var factors = [];
  for (var i = 2; i < n; i++) {
    if (divisible(n,i)) {
      if (isPrime(i)) {
        factors.push(i);
      }
      factor(i);
    }
  }
  console.log(factors);
}

Thank you in advance!

Answer №1

function findPrimeFactors(num) {
  function getSmallestFactor(n) {
    if (n % 2 === 0) return 2;
    for (let k = 3; k * k <= n; k += 2) {
      if (n % k === 0) return k;
    }
    return n;
  }

  let factors = [];
  let value = num;

  while (value !== 1) {
    let factor = getSmallestFactor(value);
    factors.push(factor);
    value /= factor;
  }

  return factors;
}

console.log(findPrimeFactors(28));

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

mongoose populate method does not return the expected results

My Project Objective I am currently in the process of creating a travel booking platform for a transportation company. One of the key features I am working on is displaying the name of the individual who made the booking on a specific page within the webs ...

The tubular.js Youtube video background is overlapping my other components on the site, instead of displaying behind them as intended

I recently implemented the tubular.js script on my webpage to display a YouTube video as the background. On the tubular page, there is a statement that reads: First, it assumes you have a single wrapper element under the body tag that envelops all of ...

JavaScript -Error: Unable to access the 'children' property as it is undefined

I'm currently working on creating a tree and calculating its height. The map array is properly initialized within the for loop, but when I run console.log(map+" this is map");, it displays [object Object],[object Object],[object Object],[object Objec ...

searching for trees recursively in JavaScript

I am trying to develop a function that can search through an array containing nested arrays to find a specific node with information, similar to navigating a tree structure. const data = [ { id: '1-1', name: "Factory", children: [ ...

Creating a Google Captcha with validation is a straightforward process that can enhance the

I am having issues with adding Google Captcha to my form. Despite all fields working properly, the Captcha integration seems to be causing some disruptions. I have included my code below. Thank you in advance for your help. Please also check the following ...

Retrieve the individual character styles within an element using JavaScript

I'm currently dealing with a dynamically created div that features styled characters like: <div>Hello <b>J</b>oe</div> and my goal is to identify which characters are styled (in this case, the letter J). I've already atte ...

Javascript is throwing an unexpected token error due to an HTML alteration, which is indicated by the character

Each time I make a modification to my HTML file, I encounter a javascript error saying Unexpected token '!'. It appears that any change made to the HTML file triggers a javascript error. Despite this, there is nothing incorrect with the code itse ...

What is the reason for the 'admin' page not being displayed?

After reading the MEAN MACHINE Book and following the instructions on Routing Node applications [pg - 36], I encountered an issue. The express.Router()⁴⁸ functions as a mini application where you can define routes. Let's see an example by adding ...

Ways to analyze the file extensions within an array and trigger an error?

Below is an array named $aSupportedImages containing file extensions: Array ( [0] => jpeg [1] => jpg [2] => gif [3] => png ) Another array called $values has the following structure : Array ( [vshare] => Array ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

What are the steps to implement $navigateTo() in a NativeScript Vue application?

What could be causing $navigateTo(Page) to not work? Visit this link for more information ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Arranging a 2D array of matchups to ensure an equal distribution of home and away matches for each team

I am in the process of developing a unique UEFA Champions League 24 'Swiss Model' tournament with 36 teams. Each team is set to compete against 8 different opponents, resulting in a total of 144 matches. I already have a list of matchups prepared ...

Creating a stylish background gradient between two handles on a jQuery Slider with CSS

After watching a presentation by Lea Verou on CSS Variables titled CSS Variables: var(--subtitle);, I was inspired to create a gradient effect between jQuery Slider handles: $(function() { var max = 400; var $slider = $('.slider'); funct ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

LocalStorage is designed to hold only the most recent data input

As I work on developing an app using PhoneGap for iOS, I encounter an issue with LocalStorage. After entering and storing a username and password on my iPad, I close the app, open it again, and enter a new set of login credentials. However, when inspecting ...

What is the best way to incorporate an 'is_logged_in' condition into a django python if statement?

This views.py file is for the search functionality in my Django project. @csrf_exempt def search(request): if request.method == 'POST': name = request.POST.get('name') loc = request.POST.get('l ...

Electron / Atom Shell unable to locate specified module

I am completely new to npm, node, and Electron. Here is the structure of my folder: -package.json -index.html -main.js -js/myStuff.js -node_modules In the file myStuff.js, I have a line that says var chokidar = require('chokidar'); but it keep ...

An error notification has surfaced on line 11 pointing to the issue at deck[i][j]

Encountering the following error message in line 9 of my code (deck[i][j] = ...) invalid operands to binary + (have ‘char *’ and ‘char *’). Any ideas on how to resolve this? #include <stdio.h> char* symbols[4] = {"Stars", "D ...

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...