Generating prime numbers in Javascript

My attempt at generating the prime numbers less than 20 using my current knowledge is as follows:

let arr = [];

for (let x = 3; x <= 20; x++) {
  for (let i = 20; i > 0; i--) {
    if (x % i !== i) {
      arr.push(x)
    }
  }
  console.log(arr)
}

I acknowledge that there are more efficient methods available, but I prefer to start from scratch and improve my skills gradually rather than relying on shortcuts.

The purpose of the code is as follows:

  1. An outer loop starting from 3 to 20 with increments of 1.
  2. An inner loop starting from 20 to 0 with decrements of 1.
  3. The condition in the inner loop checks if the number x modulo i is not equal to i, indicating it is a prime number.

For example:

7 is prime.

7 % 7 = 0
7 % 6 = 1
7 % 5 = 2
7 % 4 = 3
7 % 3 = 4
7 % 2 = 5
7 % 1 = 6

whereas

6 is not prime

6 % 6 = 0
6 % 5 = 1
6 % 4 = 2
6 % 3 = 3    <=== because of this
6 % 2 = 4
6 % 1 = 5

The output consists of multiples of numbers between 3-20 repeated 20 times. It does not accurately generate prime numbers as intended.

Answer №1

Considering that clarity is valued over efficiency by the OP, there is a straightforward observation that can significantly reduce the search process without introducing any notable complexity: any non-prime number must have a prime divisor. This allows us to focus the divisibility check on smaller primes that have already been identified.

To put it simply...

let arr = [];

for (let x = 3; x <= 20; x++) {
  // only check against previously discovered primes
  let isPrime = true;
  for (let i = 0; i < arr.length; i++) {
    if (x % arr[i] === 0) {
      isPrime = false;
      break;
    }
  }
  if (isPrime) arr.push(x)
}

console.log(arr)

Summarized succinctly...

let primes = [];

for (let x = 3; x <= 20; x++) {
  if (primes.every(prime => x % prime !== 0)) primes.push(x)
}

console.log(primes)

Answer №2

There are a couple of flaws in the logic that can be optimized and fixed.

  • The outer loop can increment by 2 (since evens aren't prime).
  • The inner loop doesn't need to start larger than x; instead, start from x-1 and go to 1.
  • Add a flag (np) to track if the number isn't prime.
    • If x % i is 0, then flag it as np and break (if a number (x) is divisible by a smaller number (i), it isn't prime).
    • Only add x if it's not flagged as np (or prime).
    • Reset the flag for each x.

let arr = [];
let np=false
for (let x = 3; x <= 20; x+=2) {
  np=false
  for (let i = x-1; i > 1; i--) {
    if (x % i === 0) {
      np=true
      break
    }
  }
  if(!np){
    arr.push(x)
  }
}
console.log(arr)

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

Is it possible to create a secondary <li> dropdown menu using JavaScript or jQuery from a PHP-generated dropdown menu?

Using a foreach loop to query the database, I have created a drop-down menu. Now, what I want is that when I select a subitem from the menu using JavaScript, I can retrieve the value and make an Ajax request to fetch all the values corresponding to the su ...

Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript? For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing ...

Arranging hierarchical data in JavaScript

After populating the hierarchy data, it is structured as follows: Here is a screenshot: I am looking to sort this data. Currently, I have a flat data object for rendering purposes. For example, my rendering object looks like this: renderedobjects=[ {1,. ...

Proper approach for mapping JSON data to a table using the Fetch API in a React.js application

Struggling to map some elements of JSON to a Table in Customers.jsx, but can't seem to figure out the correct way. How do I properly insert my Fetch Method into Customers.jsx? Specifically managing the renderBody part and the bodyData={/The JsonData/} ...

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

What is the origin of this mysterious error?

I'm working on a function to format various types of variables and utilize a toString() method. It's handling complex objects, arrays, and circular references flawlessly. However, when testing it on a jQuery object using format($("body")) with l ...

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

Ways to split up array objects in an axios GET request

Hello, I recently implemented an AXIOS GET request that returns an array of objects. However, the current example I am using retrieves the entire array at once, and I need to separate the objects so that I can work with them individually. class CryptoAP ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

Information not displaying correctly on the screen

My latest project is a recipe app called Forkify where I am utilizing JavaScript, npm, Babel, Webpack, and a custom API for data retrieval. API URL Search Example Get Example The app displays recipes with their required ingredients on the screen. Addit ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Vue function that inserts <br> tags for addresses

My Vue filter retrieves and combines address details with a , Vue.filter('address', (address, countryNames = []) => { const formattedAddress = [ address?.name, address?.company, address?.add1, address?.add2, address?.town ...

Guide on Implementing jQuery UI Autocomplete with Chrome's Speech Input Feature

I have recently discovered a cool feature in Chrome that allows users to dictate into any input field using speech input. Learn more here. It's easy to add this feature in Chrome: <input type="text" x-webkit-speech="x-webkit-speech" /> <!-- ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...