Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
javascript prime number query

this is my code :

  var num = parseInt(105);
  // debugger
  if (num < 1) {
    console.log("=> 0 or minus value is not a prime number", num);


  } else if (num == 2) {
    console.log("=> 2 is a prime number", num);


  } else if (num > 2) {

    for (i = 2; i < num; i++) {
      if (num % i == 0) {
        console.log("this is a not prime number as it is devided by zero");
        break


      } else {
        console.log("this is a prime number")

      }
    }
  }

in this code why else statement is showing the output when I put any odd numbers where I already worte the break statement for stopping the loop break.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If the number is not divisible by a particular i then your else condition is being executed. Change num to 5 you would see this is a prime number print several times.

You can create a function (as shown below) where we first check all the is then print this is a prime number.

function isPrime(num) {
  if (num < 1) {
    console.log("=> 0 or negative values are not prime numbers", num);
  } else if (num === 2) {
    console.log("=> 2 is a prime number", num);
  } else if (num > 2) {
    for (let i = 2; i < num; i++) {
      if (num % i === 0) {
        console.log(`this is a not prime number as it is divisible by ${i}`);
        return;
      }
    }
  }
  console.log("this is a prime number");
}

isPrime(105);

Or you can store the result in a variable, and at the end of the loop print this is a prime number if the variable wasn't set.

const num = 105;
if (num < 1) {
  console.log("=> 0 or negative values are not prime numbers", num);
} else if (num === 2) {
  console.log("=> 2 is a prime number", num);
} else if (num > 2) {
  let isPrime;
  for (let i = 2; i < num; i++) {
    if (num % i === 0) {
      console.log(`this is a not prime number as it is divisible by ${i}`);
      isPrime = false;
      break;
    }
  }
  if (isPrime !== false) {
    console.log("this is a prime number");
  }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!