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

Angular view fails to update after form submission when using ngDialog to change the scope

After starting my Angular journey, I decided to challenge myself by creating a comprehensive todo app for educational purposes. I seem to be missing something pretty basic, although I can't quite put my finger on it. It seems like there might be an is ...

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Step-by-step guide on duplicating a div a set number of times

I am looking to replicate the entire div multiple times (e.g., on an A4 paper, top left corner, top right corner, bottom left corner, and bottom right corner). <script language="javascript" type='text/javascript'> function updateD ...

Utilize mapping for discriminated union type narrowing instead of switch statements

My objective is to utilize an object for rendering a React component based on a data type property. I am exploring ways to avoid utilizing switch cases when narrowing a discriminated union type in TypeScript. The typical method involves using if-else or sw ...

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...

What is the meaning of "bootstrapping" as it relates to Angular 2?

I found a question that is similar to mine, but I think my case (with version 2) has enough differences to warrant a new discussion. I'm curious about the specific purpose of calling bootstrap() in an Angular 2 application. Can someone explain it to ...

clearInterval function is not functioning

Could this be a simple syntax error causing my frustration? The resizeTime variable seems to persist despite multiple attempts to clear it using clearInterval. Any thoughts on what may be going wrong here? Below is the code snippet: var resizeTime; // e ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

The function of TypeScript map is not working properly

Encountering the error message "data.map is not a function" while trying to map data from a REST API request returning JSON data. It appears that the issue may stem from the data structure, as it seems like the returned data should be accessed with data.da ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

What might be causing the issue of a click handler not registering during the initial page load when using Enquire.js

I am experimenting with different effects on various breakpoints. My main goal is to achieve the following behavior: when a category is clicked from the list within 720px, the category list should fade out while the data is revealed in its place. However, ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

Only when the condition is satisfied in AngularJS will I include JSON data

I have a JSON file named components.json containing information about various board spaces: {"components": { "boardSpaces": [ {"name":"GO!", "price":0, "position":0, "type":"go"}, {"name":"Mediterranean Avenue", "type": "property", "pr ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...