Use Flag to change status

Study notes for JavaScript

Posted by Rui on 11-11-2021
Estimated Reading Time 1 Minutes
Words 278 In Total
Viewed Times

Judgement of Prime Number

Q: User input a number, determine if the number is a prime number

First Try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function vertify(){
var num = document.getElementById("num").value;
console.log(num);
if(num <= 2){
alert("Not a Prime Number");
};
for(var i = 2 ; i < num; i++){
if (num % i == 0){
alert("Not a Prime Number");
break;
}
if( i == num - 1){
alert("Is a Prime Number")
}
}
}

Feedback

I had trouble of deciding where to put the alert(“Is a Prime Number”), it should be outside the for() loop, but if I put it outside, the statement will still be gone through even when (num % i == 0) and break from that if(). it should not be like this. My solution is to see if i went to the last cycle, aka (i == num - 1), it means the previous outcomes are all negative.
Obviously, it’s not a good solution. We can use ‘flag’ to present the status of num, defalt setting is num is a prime number, if we ever come across any situation deciding it’s not a prime number, we can just change the flag. The final output depends on flag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function vertify(){
var num = document.getElementById("num").value;
console.log(num);
var flag = true;

if (num <= 1){
flag = false;
}else{
for (var i = 2; i < num; i++){
if(num % i == 0){
flag = false;
}

}
}

if (flag){
alert("Is a Prime Number")
}else{
alert("Not a Prime Number")
}
}


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !