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

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

Currently, my focus is on creating a robust slash command handler for discord.js version 13

I've been attempting to update my command handler to support slash commands, but I keep encountering an Invalid Form Body error when trying to activate the bot. I'm hesitant to switch handlers since I use this one for all my bots, but I can&apos ...

Launching ExpressJS and ReactJS on Heroku

Currently working on a project that combines express and react. When attempting to deploy it to Heroku via git push, I encountered an error upon checking the heroku logs. The specified webpage then shows a message indicating that it cannot locate a build ...

Ensure modifications to a variable are restricted within an if statement

I am struggling to find a way to globally change a variable within an if statement and ensure that the modifications persist. User input: !modify Bye var X = "Hello" if (msg.content.includes ('!modify')) { X = msg.content.replace('!modi ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

Extract different properties from an object as needed

Consider the following function signature: export const readVariableProps = function(obj: Object, props: Array<string>) : any { // props => ['a','b','c'] return obj['a']['b']['c'] ...

The validation feature is ineffective when used with Material UI's text input component

I need a function that can validate input to make sure it is a number between 1 and 24. It should allow empty values, but not characters or special symbols. function handleNumberInput(e) { const re = /^[0-9\b]+$/; const isNumber = re.test(e.target.val ...

A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out. Below is the code snippet: import React from "react"; import ReactDOM from "react-dom"; import { TextField, Bu ...

Mastering the art of passing props in VueJS

My setup in the App is quite straightforward, with two main components: The HelloWorld component and a dialog component. The dialog component receives props from the HelloWorld component. The data in the HelloWorld component is rendered by looping over an ...

Retrieving variables using closures in Node.js

I have been developing thesis software that involves retrieving variables within closures. Below is the code snippet written in node.js: var kepala = express.basicAuth(authentikasi); // authentication for login function authentikasi(user, pass, callback ...

The ng-submit() directive in Angular does not trigger submission when the "Enter" key is pressed in a text field

I have created a basic form using Angular where I want the ng-click function (updateMsg({name: name,room: room})) to be triggered when the user enters a value and then presses enter key. Unfortunately, the current code does not work as expected. The funct ...

Pass a reply from a function to a route in expressjs

I'm currently working on a project where I need to retrieve JSON data from an API using an Express server in Node.js. However, I'm facing some confusion regarding how Node.js manages this process. In my code, I have both a function and a route de ...

Achieving second class using jQuery from a choice of two

Looking for assistance with retrieving the second class from an element that has two different classes. I attempted to use the split method but encountered some issues, can anyone provide guidance? js_kp_main_list.find('li#kp_r_04').addClass(&ap ...

How to allow users to input strings on web pages with JavaScript

I created a Language Translator using java script that currently translates hardcoded strings in an HTML page. I want to enhance its flexibility by allowing users to input a string into a textbox/textarea for translation. Any assistance would be greatly a ...

What methods can I use to create a peer-to-peer communications platform with PHP, MySQL database, and JavaScript?

Currently, I am encountering the challenge of creating a communication channel between two users on a website (such as a gaming site) using only the technologies specified in the title. I recently created an online chess platform with the aim of allowing ...

I encountered an SyntaxError while working with Ionic. The error message reads: "Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)."

Here's the code that is causing me trouble: this.http.get('http://localhost/....) .map((res) => res.json()) .subscribe(( this.navCtrl.push(OtpPage,{mobileno:this.mobile}); }, (err) => { console.log(err ...