js判断一个素数能被几个9整除完整代码
时间: 2023-11-12 09:03:43 浏览: 72
以下是 JavaScript 判断一个素数能被几个9整除的完整代码:
```javascript
function isPrime(num) {
if (num < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function countNines(num) {
let count = 0;
while (num % 9 === 0) {
count++;
num /= 9;
}
return count;
}
function primeDivisibleByNines(num) {
if (!isPrime(num)) {
return "The input number is not a prime number.";
}
const count = countNines(num);
if (count === 0) {
return "The input number is not divisible by 9.";
}
return `The input number is divisible by 9 for ${count} times.`;
}
console.log(primeDivisibleByNines(17)); // The input number is not divisible by 9.
console.log(primeDivisibleByNines(19)); // The input number is not divisible by 9.
console.log(primeDivisibleByNines(81)); // The input number is not a prime number.
console.log(primeDivisibleByNines(97)); // The input number is not divisible by 9.
console.log(primeDivisibleByNines(729)); // The input number is divisible by 9 for 1 times.
console.log(primeDivisibleByNines(6561)); // The input number is divisible by 9 for 2 times.
```
这段代码定义了三个函数:
- `isPrime(num)`:判断一个数是否为素数;
- `countNines(num)`:计算一个数能被几个 9 整除;
- `primeDivisibleByNines(num)`:判断一个素数能被几个 9 整除。
函数 `primeDivisibleByNines(num)` 先判断输入的数是否为素数,如果不是,则返回错误信息;如果是,则调用函数 `countNines(num)` 计算能被几个 9 整除。如果结果为 0,则返回错误信息;否则返回结果字符串。最后,代码通过调用 `console.log()` 打印出了几个测试用例的结果。
阅读全文