Perhaps a Boolean condition enclosed in an If Statement nested inside a loop

After reviewing whether a number is prime using the Or Boolean statement, the results are unexpected. Instead of completing the check and returning only prime numbers, the function returns the entire array.

function sumPrimes(num) {
  var arr = [];

  var prime;
  for(var i = 1; i <=num; i++){
   if(i%2 !== 0 || i%3 !== 0 || i%5 !== 0){
     arr.push(i);
   }
  }
  return arr;
}

sumPrimes(10);

Answer №1

If you're looking for an efficient way to find prime numbers, consider using a custom prime number algorithm like this:

function findPrimes(limit) {
  var sieve = [], index, multiple, primes = [];
  for (index = 2; index <= limit; ++index) {
      if (!sieve[index]) {
          // Found a prime number
          primes.push(index);
          for (multiple = index << 1; multiple <= limit; multiple += index) {
              sieve[multiple] = true;
          }
      }
  }
  return primes;
}

You can then calculate the sum of these prime numbers efficiently using the reduce method

var calculateSumOfPrimes = function(number) {
  var primesList = findPrimes(number)
  var sum = primesList.reduce(function(total, primeNum) {
    return total + primeNum
  }, 0)
}

Answer №2

The desired logic can be achieved using one of the following conditions:

if (i%2 !== 0 && i%3 !== 0 && i%5 !== 0) // not divisible by 2, 3, or 5
                                         // and not divisible by 5

or

if (!(i%2 === 0 || i%3 === 0 || i%5 === 0)) // not divisible by 2, 3, or 5

Note that this logic is applicable for prime numbers up to 48.

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

Utilizing "x-forwarded-for" in Node.js without dependency on Express (if feasible)

In the midst of my latest project, I find myself in need of retrieving the remote IP address within a Node.js http.createServer((req,res)=>{}) function. Despite delving into the API documentation for Node.js itself, my search proved futile. Resorting to ...

Obtaining every PDF file linked within a designated div/table section of a website

Is there a way to download all PDFs linked in a table on a webpage using javascript? Edit: To clarify, I am trying to find a solution where Javascript can automatically download all the PDFs contained within a specific table on a webpage viewed in a brow ...

Dividing the results of two arrays obtained through mysqli_fetch_array

I've come up with the following code snippet: while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) { print_r($data['course']); } This results in the following output: Array ( [user_id] => 57 [course] => ...

Ways to retrieve the latest message from a particular discord channel

Struggling to retrieve the latest message from one channel by sending a command in another channel. I envision the process to be like this: Channel 1: (I enter) "Get last message of channel 2" Channel 2: Last message is ("Hello"); Channel 1: I receive th ...

How can you refresh the source element?

Is there a way to make the browser reload a single element on the page (such as 'src' or 'div')? I have tried using this code: $("div#imgAppendHere").html("<img id=\"img\" src=\"/photos/" + recipe.id + ".png\" he ...

Updating button appearance upon pressing in React Native

Is there a way to make the style of a button in my app change when it is being pressed? What methods are usually recommended for achieving this? ...

When a parent document is deleted, Mongoose automatically removes any references to child documents

Greetings everyone, thank you for taking the time to read my query. I am looking to remove a child object that is referenced in a parent object. Below is the structure: const parentSchema: = new Schema({ name: String, child: { type: mongoose.Schema. ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

Guide on Developing a JavaScript Library

After creating several JavaScript functions, I noticed that I tend to use them across multiple projects. This prompted me to take things a step further and develop a small JavaScript Library specifically for my coding needs. Similar to popular libraries l ...

Establishing a connection to an active process within Winappdriver with the utilization of JavaScript

As someone who is fairly new to working with JS and WinAppDriver, I am currently facing a challenge with testing a Windows-based "Click Once" application built on .Net. To launch this application, I have to navigate to a website through Internet Explorer a ...

Display a php page inside a DIV element using jQuery

I'm facing an issue with integrating a PHP page into a div after an Ajax call. My goal is to load page.php into the div with the id of content within the Ajax success function. <div id="content"></div> function load(a, b) { $.ajax ...

Optimal Approach for Managing ASP.NET Ajax Modal with MouseOver - Data Retrieval Only Upon Request

I'm interested in developing a modal popup that dynamically fetches the data inside it upon mouseover, instead of preloading all the data beforehand. Are there any scripts or frameworks available that would simplify this task? ...

Assign object values only using Object.assign

I have two objects. One serves as the original source object, while the other is a deep copy of the source object with potentially different values. For example: { id: 123, people: [{ name: "Bob", age: 50 }, { name: "Alice", ...

Issue with Ajax request not functioning properly upon reloading the page

My home page is designed in PHP and includes checkboxes for the brand and store list. At the end, there's a submit button provided below. <html> <head> <title>Insert title here</title> <script src="http://ajax.googleapis.co ...

Show or hide side menu depending on when a div reaches the top of the

I have a side menu that opens when a specific div reaches the top of the window. The menu includes a toggle button for opening and closing it. However, I am encountering an issue where the script keeps closing the menu on scroll even after manually openi ...

Guide to deleting a user from a list in AngularJS

I created a confirm button to delete a user from the list, but for some reason it's not working. Could someone please review my JavaScript code to see if there are any mistakes? Here is the JavaScript code: $scope.doDelete = function(user) { ...

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Leveraging information within a handlebars function

I want to create a Handlebars helper that will allow me to show an element x number of times, with the value of x determined by the data passed to the template. I came across some code on this page that uses the #times function. However, instead of the lo ...

Multiple calls being made to $on function within $rootScope

After my webservice completes data retrieval, I trigger $rootScope.$emit('driver-loader');. This signal is only sent from this particular location. In order to listen for 'driver-loaded', I have the following code snippet: var watchDri ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...