Prime number checking in javascript only number 9 is giving wrong output - javascript

I am trying to make a javaScript function to check the prime number. It's perfectly working for lot of all the numbers I've tested but only comes wrong output when the value is 9.
Could you please anyone check below code and advise?
const primeDetector = function (inputNumber) {
if (inputNumber < 1) {
console.log("Your input is not a prime");
}
if (inputNumber === 1) {
console.log("Your input is Neither prime nor composite");
}
if (inputNumber === 2) {
console.log(`${inputNumber} is a prime number`);
} else if (inputNumber > 2) {
for (var i = 2; i < inputNumber; i++) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
break;
} else {
console.log(`${inputNumber} is a PRIME number`);
break;
}
}
}
};
primeDetector();

As far as I can tell your function only checks if a number is even or odd, because you break the loop instantly. You are just checking i=2.

The problem is that you are forgetting that you are doing your check in a loop. You treat it as if it is not in a loop:
for (var i = 2; i < inputNumber; i++) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
break;
} else {
console.log(`${inputNumber} is maybe a PRIME number, if I don't say it is not a prime number at the end then it is PRIME, right now I'm not sure yet`);
// break; // <-- this break is the bug
}
}
Remember, this is a loop. If the number is not divisible by i then it does NOT mean it is a prime but it just means you have not tested with all the values of i yet. You still need to complete the loop to test all the values of i.
If you want to only print one message when it is a prime you need to remember if you have passed the test or not. In programming, remembering means using memory and using memory means using a variable:
var is_prime = true;
for (var i = 2; i < inputNumber; i++) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
is_prime = false;
break;
}
}
// We only know if the number is a prime HERE
// not inside the loop above
if (is_prime) {
console.log(`${inputNumber} is PRIME`);
}

The logic of the loop is very simple. Iterate from i = 2 until i = inputNumber - 1, see if inputNumber is divisible by i. If yes, definitely not a prime number. If no, keep going until we are sure it is not divisible by ANY of i in that range.
const primeDetector = function (inputNumber) {
let isPrime = true;
if (inputNumber < 1) {
console.log("Your input is not a prime");
isPrime = false;
}
if (inputNumber === 1) {
console.log("Your input is Neither prime nor composite");
isPrime = false;
}
if (inputNumber === 2) {
console.log(`${inputNumber} is a prime number`);
isPrime = true;
} else if (inputNumber > 2) {
for (var i = 2; i < inputNumber; i++) {
console.log(`Checking if ${inputNumber} is divisible by ${i}`);
if (inputNumber % i == 0) {
console.log(`Opps. ${inputNumber} is divisible by ${i}. ${inputNumber} is then NOT a prime number`);
isPrime = false;
break; // Found one divisible, definitely not a prime number. No need to continue, just exit the loop
} else {
console.log(`${inputNumber} is not divisible by ${i}. Maybe a prime number. Wail till end ya`);
// break;
}
}
isPrime? console.log(`${inputNumber} is a prime number`) : console.log(`${inputNumber} is not a prime number`);
}
};
primeDetector(9);
primeDetector(11);

Related

Is this a bad way to check prime number using Javascript

const input = 3;
let isPrime = true;
outer: for(let i = 2; i < input; i++){
for(let j = 2; j < input; j++) {
if((i * j) === input) {
isPrime = false;
console.log(`${input} is Not a prime number`);
break outer;
}
}
}
if(isPrime) {
console.log(`${input} is a prime number`); }
Personally, I think this is not the right way, even though I could've done it in an easier way, I approached the problem like so.
I needed some feedback from my seniors, can I get a code review?
Nested loops are mostly time consuming solutions. If you have an other option you need to probably do that. In this case you using nested for loops to determine prime number. But you can do it with only one for loop.
const number = 3
let isPrime = true;
// check if number is equal to 1
if (number === 1) {
console.log("1 is neither prime nor composite number.");
}
// check if number is greater than 1
else if (number > 1) {
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${number} is a prime number`);
} else {
console.log(`${number} is a not prime number`);
}
}
For more information you can check these links:
Why nested loops are bad practice
Finding a prime number

I write a function to find the prime number , but it's not working because I'm not able to break the loop

function isPrime(n) {
if (n == 1 ) {
return (`${n} is niether a prime number nor composite number`)
}
else if( n < 1){
return (`${n} is not a prime number`)
}
else{
for (let i = 2; i < n; i++) {
if( n % 2 == 0){
return result = `${n} is not a prime number`
break;
}
else{
return result = `${n} is a prime number`
}
}
}
}
console.log(isPrime(15))
I write a function to find the prime number , but it's not working because I'm not able to break the loop
Although answer by Dave addresses the question I would suggest this stack overflow answer as an better alternative.
https://stackoverflow.com/a/38643868/10738743
There are two glitches preventing your function working as intended.
the loop which tests for primeness is repeating n%2 on each iteration, which will evaluate the same, regardless of the value of i in the loop. Instead, you should be testing to see whether n%i is true.
With that fixed, the final return (which only happens if all non-prime conditions have been rejected with earlier returns) should be outside of any block as it becomes the default return value.
your code functions fine with the minor changes suggested above incorporated:
function isPrime(n) {
if (n == 1 ) {
return (`${n} is niether a prime number nor composite number`);
}
else if( n < 1){
return (`${n} is not a prime number`)
}
else {
for (let i = 2; i < n; i++) {
if( n % i == 0){
return result = `${n} is not a prime number`
// break; // (return breaks anyway)
} // end if
}// end for i;
} // end else
return result = `${n} is a prime number`; // default after no earlier rejection
}
console.log(isPrime(15));

isPrime function logs 15 as true (15 is not a prime number)

function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){ return false
} else if (num === 2) {
return true
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false
} else {
return true
}
}
}
Tried changing the conditional of the for loop but still comes out as true.
Wait until the whole loop finishes before returning true, otherwise you only check the first iteration and make a decision right away whether the input is prime before checking all the rest of the numbers. Also surely you don't need to iterate the entire length of the number, Math.ceil(num/2) + 1 should suffice. This is because there's no point to ever check if anything larger than half of a number will factor into that number. (This will make a big impact on larger numbers)
function checkPrime(){
var num = document.getElementById("num").value;
var result = document.getElementById("result");
var arr=[];
if (num.length===0)
result.innerHTML = "Please, specify a number.";
else if (num<0)
result.innerHTML = "Please, specify a positive number.";
else
result.innerHTML = isPrime(num).toString();
return false;
}
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2)
return false;
else if (num === 2)
return true;
const max = Math.ceil(num/2) + 1;
for (let i = 2; i < max; i++) {
if (num % i === 0)
return false;
}
return true;
}
<form onsubmit=" return checkPrime()">
<label>Enter a number check prime</label>
<input type="number" id="num" name="num"><br>
<input type="submit" value="Submit" id="submit">
<div id="result"></div>
</form>
This means you are testing any number entered to return a bool (true/false) if it is a prime number.
I would modify your code a little bit to give this function a correct answer.
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){
return false
}else if(num==2){
return true;
}else{
for (let i = 2; i < num; i++) {
if (num % i == 0) {
return false;
//break;
}
}
return true;
}
}

JavaScript Loops With If and Else

how come the following is not accurately logging whether a number is prime or not?
function isPrime2(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return console.log(false); break;
} else{return console.log(true)}
}
}
isPrime2(33)returns true, even though it is a prime number.
If i = 2, then the console will log true since 33/2 = 16.5
But since the loop isn't over, the next i value is i=3,
so shouldn't the console log false and then break out of the loop completely, leaving the final answer to be false?
There are two problems here.
Your logic is broken
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
} else {
return console.log(true)
}
}
}
isPrime2(33);
i starts at 2.
if(num % i === 0) is false, so we go to else
else{return console.log(true)} causes it to log true and exit the function.
Your failure condition is triggered when the first test fails instead of waiting for the loop to finish with a success condition for any of the tests.
33 is not a prime
It is divisible by 3 and 11.
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
}
}
return console.log(true)
}
isPrime2(33);

Issue with prime number test javascript

I'm a beginner and trying to complete a prime number test but I'm running into an issue. Here is what I have:
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
if (n < 2) {
alert(n + " is not a prime number.");
}
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
alert(n + " is not a prime number.");
break;
}
else {
alert(n + " is a prime number.");
break;
}
}
It's running correctly except an alert won't pop up if I input 3 or 2 and any number with a 3 in it is coming back as a prime number even if it isn't. Other than that all of my tests have worked.
Ahhh, your problem is the way you've structured the loop. You're breaking out regardless of if the check's completed.
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
var isPrime = true;
if (n < 2) {
isPrime = false;
} else if (n < 4 && n >= 2) {
// isPrime is already true
} else if (n % 2 === 0) {
isPrime = false; // no divisor of 2 can be prime
} else {
var sqrtN = Math.sqrt(n);
for (var i = 3; i <= sqrtN; i = i + 2) {
if (n % i === 0) {
// Only break out of the loop if a match is found
isPrime = false;
break;
}
}
}
if (isPrime) {
alert(n + " is a prime number.");
} else {
alert(n + " is not a prime number.");
}
Or, a perhaps more organized solution:
function isPrime (n) {
n = parseInt(n);
var i;
if (Number.isNaN(n)) {
return false;
} else if (n < 2) {
// 1 is not prime
return false;
} if (n < 4) {
// 2 and 3 are prime, so why not skip checking them?
return true;
} else if (n % 2 === 0) {
// No number divisible by 2 is prime.
return false;
} else {
// This won't change, so calculate it once as suggested by Weather Vane.
var sqrtN = Math.sqrt(n);
// 4, 6, 8... All divisible by 2, and would be caught by initial check.
for (i = 3; i < sqrtN; i = i + 2) {
// Not a prime if it's evenly divisible.
if (n % i === 0) {
return false;
}
}
// Otherwise prime.
return true;
}
}
Of course. If n % i is not 0, it means that i does not divide n, but it does not mean n is prime. You must check all i in order to say that.
Moreover, don't recalculate expensive Math.sqrt(n) at each iteration. And be aware of NaN.
var n = Number(prompt("Input the number you want to check for prime:"));
function isPrime(n) {
if (n < 2 || !n) return false;
for (var i = 2; i*i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
alert(n + " is " + (isPrime(n) ? "" : "NOT ") + "a prime number.");
Of course, this algorithm is exponential (pseudo-polynomial). Don't use it for big n. Instead, see e.g. Miller–Rabin primality test or AKS primality test, which are polynomial.
var UI = window.prompt("Enter a whole number to test as a prime number: \n", "0");
var TV = parseInt(UI, 10);
var HITS = 0;
var DD = TV;
while (DD > 0) {
if (TV % DD === 0) {
HITS++;
}
DD--;
}
if (HITS > 2) {
document.write(UI + " is a NOT prime number");
} else {
document.write(UI + " is a prime number");
}
Please have reference to old questions asked in stackoverflow
link to the old question

Categories