<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 特点:只能被1和自身整除,不能被2到nun-1的数字整除
// function isPrime(num){
// for(var i=2;i<num;i++){
// if(num%i==0){
// return false
// }
// }
// return true
// }
// alert(isPrime(3))
// alert(isPrime(123))
// 更高效的质数判断
// 1.对于每个数n,其实并不需要从2判断到n-1
// 一个数可以进行因数分解,那么分解时得到的两个数一定是一个小于sqrt(n)一个大于等于sqrt(n)
// 比如16=2*8;16=4*4 2<4和8>4
// 所以其实我们遍到等于sqrt(n)即可
// 封装函数判断质数
function isPrime(num){
var temp = parseInt(Math.sqrt(num))
console.log(temp)
// 循环判断
for(var i=2;i<=temp;i++){
if(num%i==0){
return false
}
}
return true
}
console.log(isPrime(289))
console.log(isPrime(3))
console.log(isPrime(16))
console.log(isPrime(123))
</script>
</body>
</html>