Home > OS >  Find a prime number
Find a prime number

Time:11-16

I just want to know this code is working properly .


let number = Number(prompt("Enter the number : "));

for(i= 2; i < number ; i  ){
        if(number % i == 0 ){
                alert(
                        `${number} is not a prime number.`
                )
                break;
        }else{
                alert(
                        `${number} is a prime number.`
                )
                break;
        }
 }

But when I put <= between i and number I just thought that it will show different answer. Because in equal to loop i will also divide with number and the reminder goes 0 so it should also give prime to every number with using <= , but its not . So I want to know how this logic is performing correct even with <= .

I just expected that it will throw different answer in case of replacing < with <= but its not.

CodePudding user response:

You always reach 1 of the 2 break statements during the for loop's first iteration.

Your code

let number = Number(prompt("Enter the number : "));

for (i = 2; i < number; i  ) {
    if (number % i == 0) {
        alert(
            `${number} is not a prime number.`
        )
        break; //<---
    } else {
        alert(
            `${number} is a prime number.`
        )
        break; //<---
    }
}

simplifies to

let number = Number(prompt("Enter the number : "));

for (i = 2; i < number; i  ) {
    if (number % i == 0) {
        alert(`${number} is not a prime number.`)
    } else {
        alert(`${number} is a prime number.`)
    }
    break; //<---
}

because, regardless of whether number % i == 0 is true or false, break will be called after the appropriate alert() is called.

Since break is always called after the first iteration of the for loop, we can simplify further by removing the for loop.

let number = Number(prompt("Enter the number : "));

let i = 2;
if (number % i == 0) {
    alert(`${number} is not a prime number.`)
} else {
    alert(`${number} is a prime number.`)
}

which simplifies to

let number = Number(prompt("Enter the number : "));

if (number % 2 == 0) {
    alert(`${number} is not a prime number.`)
} else {
    alert(`${number} is a prime number.`)
}

so your current logic essentially says "number is prime unless it is divisible by 2 (with no remainder)".

For a number to be prime, it must be indivisible by all numbers between 1 and itself so you can't know if number is prime until after the for loop has finished. Therefore, you need a new variable (such as let foundDivisor = false;) declared above the for loop to keep track of whether or not any such divisor was found. During each iteration you can do foundDivisor = true; if number is divisible by i (else do nothing). Then, after the for loop, you can use !foundDivisor to check if the number was prime or not.

  • Related