function prime_number()
{
var num, i, c, flag = true;
num = parseInt(document.getElementById("one").value);
for(i = 2; i <= num - 1; i )
{
if(num % i === 0)
{
flag = false;
break;
}
if (flag === true)
var c = "It is a prime number";
else
var c = "It is not a prime number";
}
document.getElementById("two").value = c;
}
THIS IS THE CODING FOR FORM
<form>
<input type="number" id="one" name="one" placeholder="Enter a positive number"><br>
<input type="text" id="two" name="two"><br>
<input type="button" id="submit" name="submit" value="CHECK" onclick="prime_number()"><br>
</form>
I've tried the ALERT method to show the text "THIS IS A PRIME NUMBER" or "THIS IS NOT A PRIME NUMBER" and that worked.
CodePudding user response:
Because your assignments of c
are withing the for loop, when the loop breaks your assigmnents don't get executed. So, take em out of the for loop, secondly don't redefine c
with var
.
function prime_number() {
var num, i, c, flag = true;
num = parseInt(document.getElementById("one").value);
for(i = 2; i <= num - 1; i ) {
if(num % i === 0)
{
flag = false;
break;
}
}
console.log(c);
if (flag === true)
c = "It is a prime number";
else
c = "It is not a prime number";
document.getElementById("two").value = c;
}
<form>
<input type="number" id="one" name="one" placeholder="Enter a positive number"><br>
<input type="text" id="two" name="two"><br>
<input type="button" id="submit" name="submit" value="CHECK" onclick="prime_number()"><br>
</form>
P.S: You can make a more efficient check in the for loop as:
for(i = 2; i <= num/2; i )
A number cannot be divisible by more than it's half, so you don't need to test those scenarios, i.e.
x % (x/2 epsilon)
is never 0.
CodePudding user response:
Two points needs to pay attention:
- use
c = xxx
instead ofvar c = xxx
when you assign value to it - need to assign value to
c
outsidefor
loop
function prime_number()
{
var num, i, c, flag = true;
num = parseInt(document.getElementById("one").value);
for(i = 2; i <= num - 1; i )
{
if(num % i === 0)
{
flag = false;
break;
}
}
if (flag){
c = "It is a prime number";
}else{
c = "It is not a prime number";
}
document.getElementById("two").value = c;
}
<form>
<input type="number" id="one" name="one" placeholder="Enter a positive number"><br>
<input type="text" id="two" name="two"><br>
<input type="button" id="submit" name="submit" value="CHECK" onclick="prime_number()"><br>
</form>
CodePudding user response:
You should use same c = "It is a prime number" etc. because when you use var c again you declare variable c again, but it already exists.