JavaScript Prime Number Checker

What could be the reason for this code not printing anything to the console? Here is a breakdown of the issue:

Create a JavaScript function that takes an array with an integer N and checks if the given N is a prime number (meaning it is only divisible by itself and 1 without any remainder).

var n = ['2'];

function isPrime(n) {

    if (n < 2) {
      return false;
    }

    var isPrime = true;

    for(var i = 2; i < Math.sqrt(n); i += 1) {
      if (n % i === 0) {
        isPrime = false;
      }
    }

    return isPrime;
}

return isPrime(n);

Answer №1

Your code has a couple of mistakes that need to be fixed.

Firstly, it is important to iterate through every integer between 2 and Math.sqrt(n) inclusively. Otherwise, your current code will return true for 4.

Since it seems like this code is not within a function, you should remove the return from return isPrime(n), and instead use a function that displays the return value of the function, such as alert or console.log.

Keep in mind that n is actually an array, not a number. To fix this, either convert n into a number or call the function with isPrime(n[0]).

The corrected version of the code is shown below:

var n = 2;

function isPrime(n) {

    if (n < 2) {
      return false;
    }

    var isPrime = true;

    for(var i = 2; i <= Math.sqrt(n); i += 1) {
      if (n % i === 0) {
        isPrime = false;
      }
    }

    return isPrime;
}

alert(isPrime(n));

Note: You can replace n += 1 with n++ for the same result.

Answer №2

To start, the variable n is an array that you need to access the first element of and convert it into a number.

Consider changing this line:

return isPrime(n);

To this new version:

return isPrime(parseInt(n[0],10));

Additionally, make sure to adjust your for-loop condition like so:

for(var i = 2; i <= Math.sqrt(n); i += 1) { //note that i should not be <= Math.sqrt(n)

Answer №3

Here are a few minor mistakes:

var x = 2;//<--unnecessary to store x in an array

function isPrime(x) {
if (x < 2) {
    return false;
}
var prime = true;

for(var j = 2; j < Math.sqrt(x); j += 1) {
    if (x % j === 0) {
        prime = false;
    }
}
return prime;
}

isPrime(x);//<--no need for "return"

Answer №4

The reason no text appears on the screen is due to the omission of console.log.

Substitute return isPrime(n); with console.log(isPrime(n));.

Answer №5

Here is the complete code:

    var numbers = ['2', '3', '4', '5', '6', '7']; // Feel free to add more values
    function checkForPrime(num) {
        if (num < 2) {
            return false;
        }
        var isPrime = true;
        for (var i = 2; i <= Math.sqrt(num); i += 1) { 
            if (num % i === 0) {
                isPrime = false;
            }
        }
        return isPrime;
    }
    numbers.forEach(function(value) { 
        console.log('Is ' + value + ' a prime number? ' +  checkForPrime(value)); 
    });
    /*
    // Another way of looping through the array, uncomment this section and comment the one above to see it in action (both will yield the same result)
    for (index = 0; index < numbers.length; ++index) {
        console.log('Is ' + numbers[index] + ' a prime number? ' +  checkForPrime(numbers[index])); 
    }
    */

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

Issue with dependency injection arises when module definition is used

As a beginner in Angular, I'd greatly appreciate it if you could point out any rookie mistakes I may be making here. Below is my module and controller structure: (function () { 'use strict'; angular .module('myApp&ap ...

Converting & Modifying a PHP array variable into JavaScript

I've been experimenting with a fresh method for users to input data into an HTML form using the Slim Select JavaScript library. So far, I've got the basic functionality down, including a preset list of <option> items. Previously, the PHP ...

Event handler does not handle exceptions thrown from Express routes

I recently created an Express route to test my event handler for uncaught exceptions, but I'm facing an issue where the event handler is not being triggered when an error is thrown from the route code: app.js: process.on('uncaughtException&apos ...

What is the best way to calculate the difference and total of all arrays within an array?

Within my array of arrays, I am trying to subtract all inner arrays a - b and then sum the results. For example: [[10,0],[3,5],[5,8]] would result in 10 - 0 = 10, 3 - 5 = -2, 5 - 8 = -3, giving a total of 10 + (-2) + (-3) = 5; Here is my attempt: var el ...

The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty. Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message ...

JavaScript code for implementing custom commands on a Discord bot

Currently, I am working on developing a Discord bot using the Discord.js-commando library. Most of the functionalities are up and running smoothly, but I have encountered a roadblock with a specific command. The command in question is !roll, which is desig ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Prevent accordion expansion triggered by the More button click

When the More button is clicked, it should NOT expand and collapse. https://i.sstatic.net/toV1b.gif If the accordion initial state is open, it must stay open even if button is clicked, if initial state is collapsed then after the more button the accordio ...

Validating input in Angular UI Bootstrap Datepicker

I have integrated a datepicker from angular-ui/bootstrap. However, I am facing an issue where the user can freely type in the input field instead of selecting a date. Here is a snippet of my code: session.js session.getDateFormat = function() { ...

Preventing Repetition in an HTML List using JavaScript

My HTML list is populated with values from JSON, and I have a button on the page. <button onclick="printJsonList()">CLICK</button> This button triggers the following JavaScript function: function printJsonList(){ console.log(ctNameKeep); ...

Retrieving error messages and status codes using Laravel and JWT authentication

One of the challenges I'm facing is implementing JWT Auth in my Laravel + Vue SPA. When checking the credentials in my Controller, the code looks like this: try { if (!$token = JWTAuth::attempt($credentials)) { return response()- ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

Error message encountered using data.map in a React/Redux simple table leads to TypeError

I am encountering an issue with my React table initialization that is throwing a TypeError: data.map is not a function. Interestingly, the table renders successfully when I pass a simple Array like [1,2,3] instead of the certData object which is causing th ...

The inability to access data from an API is a result of the lack of a functioning

I'm encountering an issue with fetching data from an API. When I try to map through my array of data, I receive an error message stating that 'map is not a function'. I fetched the data on the index page and passed it as props to the CoinLis ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Is it possible to dynamically change the object name using $.ajax function and pass it as a

I'm attempting to parse multiple JSON files into different objects. Here is my approach: function downloadDataSave (targetObject) { // DOWNLOAD CALCULATION BACKUP var filename, response; filename = targetObject.name + '.json' ...

Steps for switching back and forth between values within a nested object

In my application, I have developed a custom React hook called useToggles specifically for managing checkboxes and radio buttons. The implementation of this hook typically looks like the code snippet below: const useToggles = (initialValues = {}) => { ...

What is the best way to utilize the existing MUI state in order to calculate and show column totals?

I am currently in the process of developing an MUI web application to keep track of some personal data. Within this application, I have incorporated the MUI datagrid pro component to efficiently display the data with its robust filtering capabilities. In ...

Upgrading ASP.Net MVC Web Application with the latest Bootstrap version 5

After updating Bootstrap from version 3.4.1 to 5.1.3, I encountered a similar issue as the original poster in this question. Thankfully, I was able to resolve it thanks to the provided answers. Now, when I click on the hamburger icon, the Navbar expands bu ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...