Find the prime number


Posted by Christy on 2023-01-20

Write a function named isPrime and pass a parameter n, if n is prime return true, else return false

function isPrime(n) {
  if (n === 1) return false;
  for (let i = 2; i < n; i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

function isPrime(n) {
  if (n === 1) return false;
  for (let i = 2; i < Math.sqrt(n); i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

console.log(isPrime(1));
console.log(isPrime(5));
console.log(isPrime(37));









Related Posts

Object and Arrays - Reference VS Copy

Object and Arrays - Reference VS Copy

元件介紹-Day04 #  Props 向內層元件傳遞資料狀態

元件介紹-Day04 # Props 向內層元件傳遞資料狀態

Go json and embedded struct

Go json and embedded struct


Comments