There are several ways of checking if a given number is prime or not. I want to find it in by own way and if the given number is not prime, I am trying to find next higher prime number. so far I tried the following and can't understand why it's creating infinite loop. Could you please correct my code. Or tell me what wrong I am doing here.
function myFunction(a){
for(i=2; i<=a; i++){
if(a % i != 0){
console.log(" Prime ")
}
else{
a++ // creates infinite loop
if(a % i == 0){
console.log("not prime")
}
else{
console.log("prime")
}
}
}
console.log(a)
}
myFunction(38) // Expected 41
what are mistakes in your code?
a
in for loop, otherwise all numbers are not prime in opinion of your function: for (i = 2; i <= a - 1; i++)
function myFunction(a) {
for (i = 2; i <= a - 1; i++) {
if (a % i == 0) {
console.log("Not Prime");
return;
}
}
console.log("Prime");
return;
}
3.you have a for
loop and many times it need a break
or return
statement, for example in there. using if
you find that the number is not prime, so break
or return
(if you want to do something for example find next prime, do that and break
or return
)
loop
and when you find there is no number that can divide a
so log
this is prime and retuen
function myFunction(a) {
for (i = 2; i <= a - 1; i++) {
if (a % i == 0) {
console.log("Not Prime");
while(true) {
a++;
let isPrime = true;
for (i = 2; i <= a - 1; i++) {
if (a % i == 0) {
isPrime = false;
break;
}
}
if (isPrime){
console.log(a);
return;
}
}
}
}
console.log("Prime");
}
myFunction(38)
isPrime
is a flag that find that if the number is prime or not, if it is true
so log
and return
at last, a better way:
function isPrime(number) {
if (number <= 1) {
return false;
}
for (var i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
function myFunction(number) {
if (isPrime(number)) {
return "Prime";
} else {
while (true) {
number++;
if (isPrime(number)) {
return number;
}
}
}
}
console.log(myFunction(39));