0

Want a way in which the program prints "is not a prime number" only one time and not many times in loop

function isPrime(n) { if (n===1){ document.write("Is not a prime number"); } else if(n === 2){ document.write("Is a prime number"); }else{ for(var x = 2; x < n; x++) { if(n % x === 0) { document.write("Is not a prime number"); } } document.write("Is a prime number"); } } isPrime(10);

15th Sep 2019, 11:49 AM
Aquib Shaikh
Aquib Shaikh - avatar
1 Answer
+ 1
You have to set a flag in order to do that. In the if block delete the print statement and write this instead Decalre flag = 0 on top So in, If(n%x==0){ flag =1; } Now come outside of everything And type this If (flag ==1) //Is a prime number else //Not a prime number
15th Sep 2019, 11:54 AM
Suhail Pappu
Suhail Pappu - avatar