I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic.

One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of all numbers within that range inclusive of those 2 numbers.

My code passes the tests for numbers 1,2,3,6 in the exercise but fails for numbers 4 & 5. Surprisingly, I am not getting any error messages from freeCodeCamp! Therefore, I'm having trouble figuring out what's wrong with my code below.

function smallestCommons(arr) {
  let allNum = [];

  for (let i = Math.min(...arr); i <= Math.max(...arr); i++) {
    allNum.push(i);
  }

  function findFactors(x) {
    let allFactors = [];
    for (let i = 1; i <= x; i++) {
      if (x % i == 0) {
        allFactors.push(i);
      }
    }
    return allFactors;
  }

  function findGCF(a,b) {
    return findFactors(a).filter(item => findFactors(b).includes(item)).reduce((p,q) => p*q);        
  }

  return allNum.reduce((a,b) => ((a*b)/findGCF(a,b)));
}

The test cases provided are as follows. My code passes 1,2,3 & 6 but fails 4 & 5.

smallestCommons([1, 5]) should return a number.
smallestCommons([1, 5]) should return 60.
smallestCommons([5, 1]) should return 60.
smallestCommons([2, 10]) should return 2520.
smallestCommons([1, 13]) should return 360360.
smallestCommons([23, 18]) should return 6056820. 

function smallestCommons(arr) {
  let allNum = [];

  for (let i = Math.min(...arr); i <= Math.max(...arr); i++) {
    allNum.push(i);
  }

  function findFactors(x) {
    let allFactors = [];
    for (let i = 1; i <= x; i++) {
      if (x % i == 0) {
        allFactors.push(i);
      }
    }
    return allFactors;
  }

  function findGCF(a,b) {
    return findFactors(a).filter(item => findFactors(b).includes(item)).reduce((p,q) => p*q);        
  }

  return allNum.reduce((a,b) => ((a*b)/findGCF(a,b)));
}

console.log(smallestCommons([1, 5])); // should return a number.
console.log(smallestCommons([1, 5])); // should return 60.
console.log(smallestCommons([5, 1])); // should return 60.
console.log(smallestCommons([2, 10])); // should return 2520.
console.log(smallestCommons([1, 13])); // should return 360360.
console.log(smallestCommons([23, 18])); // should return 6056820. 

Answer №1

Your findGCF function is not correct. In order to find the greatest common factor of two numbers, you need to identify the largest factor that can evenly divide both numbers. For example:

findGCF(60, 6)

The expected output should be 6, but your current implementation returns 36.

function findFactors(x) {
  // console.log(x);
  let allFactors = [];
  for (let i = 1; i <= x; i++) {
    if (x % i === 0) {
      allFactors.push(i);
    }
  }
  return allFactors;
}

function findGCF(a, b) {
  const bFac = findFactors(b);
  return findFactors(a)
    .filter(item => bFac.includes(item))
    .reduce((p, q) => p * q);
}

console.log(findGCF(60, 6)); // The correct answer is 6

To optimize the efficiency and fix the issue, consider creating a Set from one collection of factors and then iterate over an array of the other factor collection, starting from the largest factor and working downwards. Use the .find method to locate the first factor that is present in the Set (it could possibly be 1):

function findGCF(a, b) {
  const bFacSet = new Set(findFactors(b));
  return findFactors(a)
    .reverse()
    .find(item => bFacSet.has(item));
}

By implementing this change, your smallestCommons function will work as intended:

function smallestCommons(arr) {
  const allNum = [];

  for (let i = Math.min(...arr); i <= Math.max(...arr); i++) {
    allNum.push(i);
  }

  function findFactors(x) {
    const allFactors = [];
    for (let i = x; i >= 1; i--) {
      if (x % i === 0) {
        allFactors.push(i);
      }
    }
    return allFactors;
  }

  function findGCF(a, b) {
    const bFacSet = new Set(findFactors(b));
    return findFactors(a)
      .find(item => bFacSet.has(item));
  }

  return allNum.reduce((a,b) => ((a*b)/findGCF(a,b)));
}
console.log(smallestCommons([2, 10])) // The expected result is 2520.
console.log(smallestCommons([1, 13])) // The anticipated outcome is 360360.

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

Attempting to send JSX as a prop value

IMPORTANT UPDATE: Good news - the code is actually functioning correctly! The issue was caused by a header element obstructing the content, leading to confusion. Apologies for any misunderstandings! I am attempting to pass a simple <p> JSX tag as a ...

Sharing data from parent to child components in Vue.js: A guide to passing references

I need some help with this code snippet HTML Code: <div class="col-xs-4"> <h3 class="text-center">Incomplete task</h3> <div class="well" style="max-height: 300px;overflow: auto;"> <ul id="check-list-box" ...

Setting up an OnMouseOver event for each URL on a webpage

Is there a way to add an OnMouseOver event for all anchor tags on a page, without replacing any existing event handlers that are already in place? I'm looking for guidance on how to achieve this using JavaScript or JQuery. Any suggestions would be gr ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Calculating totals in real-time with JavaScript for a dynamic PHP and HTML form that includes quantity,

I have created a dynamic form with fields and a table that adjusts based on the number of results. Each column in the form represents name, quantity, price, and total price. The PHP and SQL code runs in a loop to populate the list depending on the number ...

How can I extract echoed information from PHP after submitting form data through jQuery Ajax?

I am looking to transfer a file from an input form to a php script using ajax and handle the response echoed by my php script. Here is my HTML form: <form id="fileUploadForm" method="POST" enctype="multipart/form-data"> <input name="fileToU ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

Author Names Missing from Book List in Locallibrary Tutorial

After spending several years working on front-end development, I've decided to delve into back-end development to expand my skill set. Following the Basic Node and Express course from FreeCodeCamp Curriculum, I am now following the MDN Express Localli ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Tips for fetching form data transmitted via HTTPS in Node.js?

As someone new to back-end security, I'm hoping for some guidance without judgement: When receiving values over HTTP in my node application, the form data is easily accessible in the request object using req.body.{name of input element} However, whe ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Retrieve a specific div element from the response data in AngularJS

Struggling to extract a specific div element from an AJAX response in Angular? Don't want the entire page content to be displayed? Tried various methods but nothing seems to work. Here's what I have attempted: $http({ method: 'GET&a ...

AngularJS promises are known for returning the object itself instead of just the resolved value

function getBusTimetable() { var waiting = $q.defer(); var busData = $http.get('https://bus.data.je/latest'); busData.success(function(response) { waiting.resolve(response); }); busData.error(function(error) { waiting.reject( ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...