What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt:

function calculatePrimeSum(num) {
// initialize an array with numbers up to the given num
  let prime = [], i = 2;
  while (prime.indexOf(num) < 0){
    prime.push(i)
    i++;
  }
// filter the array to only keep prime numbers and then sum them up
  let result = prime
  .filter(function (a){
    if(a === 2 ||a === 3 || a === 5 || a === 7){
      return a
    } else {
      return a % 2 > 0 && a % 3 > 0 && a % 5 > 0 && a % 7 > 0
  }}).reduce((a,b) => a+b)
  
  console.log(result)
  return result
}
calculatePrimeSum(977); //displays 108789 instead of 73156

In my filtering function, I check whether a number can be divided evenly by 2, 3, 5, or 7. If it leaves a remainder greater than zero, it's identified as a prime number. However, there seems to be an issue when the input is 977, resulting in an incorrect sum. Is there anyone who can identify what's causing this problem?

Answer №1

After reviewing your code, it seems that your prime number checking logic is flawed. Merely because a number cannot be divided by 2, 3, 5, or 7 does not guarantee its primality. You can actually improve this by incorporating the prime checking method from the following link: Number prime test in JavaScript. By optimizing your loop, you will only need to iterate once.

The corrected approach involves initializing a for loop starting from the smallest prime number, which is 2, and incrementing it until it meets your desired number. Within this loop, each number is checked for primality, and if it is prime, it is added to the sum.

This revised method offers several advantages:

  1. Avoids storing a large array of prime numbers in the prime array, as they are directly summed up without requiring storage. This assumes that the prime numbers are not needed for other purposes.
  2. Eliminates the need for multiple iterations compared to your previous code. The previous version involved repeated iterations within the while loop to generate all numbers, the filter for prime check, and the final summation using the reduce method.

// Adapted from: https://stackoverflow.com/questions/40200089/number-prime-test-in-javascript
function isPrime(num) {
  for (let i = 2, s = Math.sqrt(num); i <= s; i++)
    if (num % i === 0) return false;
  return num > 1;
}

function sumPrimes(num) {
  let sum = 0;
  
  for (let n = 2; n <= num; n++) {
    if (isPrime(n)) {
      sum += n;
    }
  }

  console.log(sum);
  return sum;
}
sumPrimes(977); // Outputs 73156 as expected

Answer №2

In order to determine if a number is prime, it must not be divisible by any other prime numbers. While your approach is on the right track, you need to continuously add more primes to your array for accurate results. This can be done using the following function:

const findPrimes = (n) => {
    var primes = [2];
    if (n<2) return [];
    if (n===2) return [2];
    for (let i=3;i<=n;i+=2) if (primes.every(x=>i%x)) primes.push(i);
    return primes;
  }

We begin with the first prime number and then proceed to check every second number starting from 3, since all even numbers are divisible by 2. As we iterate through i+2, we simply verify if i is divisible by any of the previously identified prime numbers. If it is not divisible (i%x), we expand our array of primes by adding i to it.

Answer №3

Presented below is an enhanced and optimized version of the Erastostenes sieve algorithm that guarantees scalability while maintaining high performance. This particular implementation includes a limit for testing numbers up to the square root of the current number:

function findPrimes(limit){
  for (var primes=[],i=1,j=0,cap=2; ++i<=limit;){
    if (i>2 && i==cap) cap=primes[j]*primes[j++];
    if (primes.slice(0,j-1).every(p=>i%p)) primes.push(i)
  }
  return primes;
}

let primeArray=findPrimes(977);
console.log("sum of primes:", primeArray.reduce((a,c)=>a+=c));
console.log("list of primes:", primeArray.join(" "));

Answer №4

Optimal and efficient solution using the prime-lib library:

import {generatePrimes, stopOnValue} from 'prime-lib';

const result = stopOnValue(generatePrimes(), 977);

let total = 0;
for (let num of result) {
    total += num;
}

console.log(total); //=> 73156

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 Typescript interface that includes keys from another interface

interface A{ a: string; b: string; c: string; // potentially more properties } interface B{ [K in keyof A]: Boolean; } What could be the issue with this code? My goal is to generate a similar structure programmatically: interface B{ ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

Sending fragmented files straight to Amazon's s3

Currently seeking straightforward examples of uploading directly to Amazon s3 in chunks without any server-side processing, except for signing the request. I have explored various options, but all examples I have found either focus solely on chunking from ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

Encountering an error message stating, "Unable to assign value to 'onclick' property"

Currently, I am at a beginner level in Javascript. While working on some exercises, I encountered an issue with the 'onclick' function as mentioned above. Despite going through other queries in this forum, I have not found a solution that works ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

The output from VScode-Code-Runner is limited to just the directory, with no additional

I have successfully set up Code Runner with the following configurations in the Executer Map: { "explorer.confirmDelete": false, "[html]": { "editor.defaultFormatter": "vscode.html-language-features" }, "[javascript]": { "e ...

Executing specific rendering procedures based on conditions for mapped data - React

When I map data in the returned render, can I then perform a conditional check on that mapped data? export default function App() { const prod = [ {'name': '1'}, {'name': '2'}, {'name': ' ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

Using Javascript within an HTML document may not provide the intended functionality

My script: <!DOCTYPE html> <html> <head> <script> $(document).ready(function () { document.getElementById("saveForm").click(); }); </script> </head> <!--<body onload="document.getElementById('saveForm&apos ...

One way to showcase a single piece of data without the need for looping is by utilizing the `

I am encountering an issue. Why does the insertAdjacentHTML("afterend") output keep looping? I only want to display "1" once, not repeatedly. var btn = document.getElementById("btnClick"); btn.addEventListener("click", function (e) { e.preventDefaul ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript? Here is some sample code: type KeyUrl<T> = T extends `/${infer U}` ? U : never; type TUrl<T> = { [k in KeyUrl<T>]: string }; // ---------------------------------- ...

What are alternative ways to communicate with the backend in Backbone without relying on model.save()?

Is there a more effective method to communicate with my backend (node.js/express.js) from backbone without relying on the .save() method associated with the model? Essentially, I am looking to validate a user's input on the server side and only procee ...

Is there a method to accurately pinpoint the specific type?

Is there a way to optimize the validateField function to narrow down the type more effectively? type TStringValidator = (v: string) => void; type TNumberValidator = (v: number) => void; type TFields = 'inn' | 'amount'; interface ...

How to pass parameters while updating parent values in VueJS using emit?

Explaining my dilemma with uploading images: In my form, users can upload images using the following code snippet: <input id="visualisation_upload" @change="onThumbnailChanged" name="visualisation_upload" accept="imag ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...