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.
You always reach 1 of the 2
breakstatements during theforloop's first iteration.Your code
simplifies to
because, regardless of whether
number % i == 0istrueorfalse,breakwill be called after the appropriatealert()is called.Since
breakis always called after the first iteration of theforloop, we can simplify further by removing theforloop.which simplifies to
so your current logic essentially says "
numberis prime unless it is divisible by2(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
numberis prime until after theforloop has finished. Therefore, you need a new variable (such aslet foundDivisor = false;) declared above theforloop to keep track of whether or not any such divisor was found. During each iteration you can dofoundDivisor = true;ifnumberis divisible byi(else do nothing). Then, after theforloop, you can use!foundDivisorto check if thenumberwas prime or not.