I am having trouble with the prime number finder in my JavaScript program. It seems to not work for certain values. What could be

I am in the process of developing a code to identify prime numbers less than n. However, I encountered an issue where the code mistakenly flags 33 and 35 as prime numbers. I am puzzled by this unexpected outcome. Here is the code that I have been working on:

function primeFinder(n) {
  let prime = []
  let index = 0
  for (let i = 2; i <= n; i++) {
    let root = Math.floor(Math.sqrt(i))
    for (let j = 2; j <= root; j++) {
      if (i % j == 0) {
        i++
        break
      }
    }
    prime[index] = i
    index++
  }
  return (prime)
}

console.log(primeFinder(35))

Despite my efforts to accurately determine prime numbers, the code does not function as intended.

Answer №1

When your inner loop stops upon finding a divisor of i, it signifies that i is not prime. Afterwards, i gets incremented and added to the prime array. This process dictates that for every non-prime value, i+1 becomes the next prime number.

To determine if you traverse through the inner loop without spotting a divisor - indicating the number as prime - you must set a flag before initiating the loop, update it when encountering a divisor, and assess the flag post-loop.

function primeFinder(n) {
  let prime = [];
  for (let i = 2; i <= n; i++) {
    let root = Math.ceil(Math.sqrt(i))
    let primeFlag = true;
    for (let j = 2; j <= root; j++) {
      if (i % j == 0) {
        primeFlag = false;
        break;
      }
    }
    if (primeFlag) {
      prime.push(i)
    }
  }
  return (prime)
}

console.log(primeFinder(35))

Answer №2

Here is a sample code for finding prime numbers:

function calculatePrimes(limit) {
  const primesList = [];

  for (let num = 2; num <= limit; num++) {
    let isPrime = true;
    const squareRoot = Math.floor(Math.sqrt(num));

    for (let divisor = 2; divisor <= squareRoot; divisor++) {
      if (num % divisor === 0) {
        isPrime = false;
        break;
      }
    }

    if (isPrime) {
      primesList.push(num);
    }
  }

  return primesList;
}

console.log(calculatePrimes(35));

Answer №3

Breaking the for statement when i is divisible by j prevents adding i to the prime list.

    for (let j = 2; j <= root; j++) {
      if (i % j == 0) {
        i++
        break // The break statement doesn't affect pushing i into primes
      }
    }
    prime[index] = i // Regardless of divisibility, i is pushed to primes 
    index++

This results in all odd numbers being listed as prime.

To optimize performance and handle large n values, use the following code to find all primes under n:

function primeFinder(n) {
  const primes = [];
  const isPrime = [];
  for (let i = 0; i <= n; i += 1) {
    isPrime[i] = true;
  }
  const root = Math.floor(Math.sqrt(n));
  for (let i = 2; i <= root; i++) {
    if (isPrime[i] == false) continue;
    for (let j = i; j <= n; j += i) {
      isPrime[j] = false;
    }
  }
  for (let i = 2; i <= n; i += 1) {
    if (isPrime[i]) primes.push(i);
  }

  return primes;
}

Avoid using divisions whenever possible as they can significantly impact performance in various programming languages. The provided code eliminates the need for divisions.

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

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Guide to displaying components based on a function's conditions

I'm working on a component that needs to display certain elements based on a condition: export interface MyComponentProps{ children: ReactNode } export const MyComponent= (props: MyComponentProps) => { const [isInitialized, setIsInitialized] ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

Guide on making a JavaScript button with both "light and dark" modes

Currently, I am attempting to change the color scheme of the page by adjusting the :root variables using a function called changeBackgrondColor(). This function is then assigned to the fontAwesome moon "button". However, when I click on the moon, the pag ...

Disable or eliminate the event listener

Working on my Angular2 application, I've set up an RxJS timer that sends notifications to users when they are logged in. The twist is, the notification should only be sent if the tab is active; otherwise, the scheduler should pause or stop. I have man ...

What is the best way to effectively use combinedLatestWith?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/country-card/country-card.component.html I am currently working on implementing a search bar in Angular that filters the "countries$" Observable based on user input. My approach involves creatin ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

How can images be resized according to screen resolution without relying on javascript?

Looking to use a large banner image on my website with dimensions of 976X450. How can I make sure that the image stretches to fit higher resolution monitors without using multiple images for different resolutions? ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

Execute a PHP script upon button click without the need to refresh the page

I'm facing an issue with integrating PHP and JavaScript. Objective: To execute a .php script when the event listener of the HTML button in the .js file is triggered without causing the page to reload. Expected outcome: On clicking the button, the PH ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Steps to turn off a Material UI CSS class for an element universally

Utilizing the Material UI Typography element with the css class MuiTypography-h1, I am seeking to globally disable its usage throughout the entire codebase. <Typography variant="h1" sx={{ width: '100px', height: '55px ...

Multiple loop in Node.js with Selenium

I just completed a node script using selenium webdriver for automated testing purposes. Below is the code snippet: var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('unders ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

How to emphasize a clicked hyperlink in AngularJS

Here's the HTML code I've been working on: <div id="Navigation" class="md-dialog-full"> <div class="products-options"> <a ng-click='addType("Physical")' href="javascript:void(0);"> < ...