0
Can anyone tell me, what is the problem in this code ?
let p = 10; //11, 13, 17, 19 let c = 2; for (p = 10; p < 21; p++) { for (c = 2; c < p; c++) { if (p % c != 0) { return p; } console.log(p + " is a prime number."); } }
5 odpowiedzi
+ 2
firstly you cannot use 'return' outside of a function...
secondly, you log p+" is a prime number" at each outer iteration ^^
to check if p is a prime number, you need to test divisibility:
if p is only divisible by itself (p % p == 0) then it's a prime...
if p is divisible by any c < p (p % c == 0) then it's not prime... then you could 'break' the loop.
to print result for p, you need to do it outside, by having set a flag to either true or false, and print " " is " or " is not " "a prime" according to that flag ;P
+ 2
no, your solution is wrong: you output p+" is prime number" each time p is not divisible by c...
check again my two previous post for explanation on how to do it, and look closely at my code solution in my second post ^^
+ 1
if (p % c) == 0 you use 'return'... wich is valid only in a function...
but in a function, by using 'return' you break both loop by exiting immediatly function ;P
you could even improve the code by only testing for divisibility by 2 and by odd number from 3 to sqrt(p)... or better by primes numbers lesser or equals to sqrt(p) ^^ (that means you've have a prime list, maybe dynamically build, to iterate over)
if you only want to print primes numbers in a range, you could do:
for (let p=10; p<21; ++p) {
if (p % 2 == 0) continue;
let m = Math.sqrt(p);
let isPrime = true;
for (let c=3; c<=m; c+=2) {
if (p % c == 0) {
isPrime = false;
break;
}
}
if (isPrime) console.log(p+" is prime");
}
0
Bro I am checking whether a number is prime or not by dividing it by number other than 1 and itself. Suppose, we divide a number lets say 10/2, here the remainder will be 0 as 10 is a composite number so according to this [p(10) % c(2)] resulting in 0 should be false as [0 != 0] should be false, even though the "if condition" is being executed? This where the problem lies. The "if condition" should not run as the condition is evaluating to false.
You copy this code and try it yourself. Please help!
0
Visph bro extremely thankful for your attention,
Please tell I replace the return keyword even though it is not showing correct answer.
let p = 10; //11, 13, 17, 19
let c = 2;
for (p = 10; p < 21; p++) {
for (c = 2; c < p; c++) {
if (p % c != 0) {
console.log(p + " is a prime number.");
}
}
}
My moto behind incrementing both p & c with a for loop is to make it dynamic for its range