challenge-algorithms-Ana-Ca.../05-é-primo/index.html

59 lines
1.7 KiB
HTML
Raw Normal View History

2021-08-18 21:00:43 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/*
Faça um algoritmo que retorne se o numero passado é primo ou não
*/
function isPrime(number) {
// implementar logica aqui
if (number === 2 || number === 3) return true
if (number % 2 === 0 || number < 2) return false
var s = 0,
d = number - 1
while ((d & 1) == 0) {
d >>= 1
++s
}
let base = 2
var x = Math.pow(base, d) % number
if (x == 1 || x == number - 1) return true
for (var i = 1; i <= s; i++) {
x = (x * x) % number
if (x === number - 1) return true
}
2021-08-18 21:00:43 +00:00
return false
}
// Resultados esperados
console.log(isPrime(2), true) // true
console.log(isPrime(3), true) // true
console.log(isPrime(4), false) // false
console.log(isPrime(5), true) // true
console.log(isPrime(6), false) // false
console.log(isPrime(7), true) // true
console.log(isPrime(8), false) // false
console.log(isPrime(25), false) // false
console.log(isPrime(31), true) // true
console.log(isPrime(2017), true) // true
console.log(isPrime(2048), false) // false
console.log(isPrime(1), false) // false
</script>
</body>
</html>