判断一个数字是否是质数
时间: 2023-05-27 10:03:51 浏览: 43
一个数字N是质数,当且仅当N大于1且N不能被2到(sqrt(N))中的任意一个整数整除。
Python代码如下:
```python
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
```
其中,`int(num ** 0.5)`是num的开平方向下取整的结果。这是因为,如果一个数N是合数,那么必然存在两个因数p和q,它们中至少一个小于或等于sqrt(N)。所以我们只需要判断小于或等于sqrt(N)的数字是否为N的因数即可。
相关问题
用js实现判断一个数字是否是质数
function isPrime(num) {
if(num <= 1) return false;
if(num === 2) return true;
if(num % 2 === 0) return false;
for(let i = 3; i <= Math.sqrt(num); i += 2) {
if(num % i === 0) return false;
}
return true;
}
console.log(isPrime(2)); // true
console.log(isPrime(3)); // true
console.log(isPrime(4)); // false
console.log(isPrime(5)); // true
console.log(isPrime(6)); // false
console.log(isPrime(7)); // true
console.log(isPrime(15)); // false
console.log(isPrime(17)); // true
C语言判断一个数字是否为质数
以下是两种C语言判断一个数字是否为质数的方法:
1. 方法一:除以比自己小的数字
```c
#include <stdio.h>
int main() {
int n, i, k = 2;
i = 2;
printf("\n请输入一个大于“2”的数:");
scanf("%d", &n);
while (i < n) {
if (n % i == 0) {
k = 1;
break;
}
i++;
}
if (k == 1) {
printf("%d不是质数\n", n);
} else {
printf("%d是质数\n", n);
}
return 0;
}
```
2. 方法二:除以比自己小的质数
```c
#include <stdio.h>
int IsPrime(int num);
int main() {
int n;
printf("\n请输入一个正整数:");
scanf("%d", &n);
if (IsPrime(n)) {
printf("%d是质数\n", n);
} else {
printf("%d不是质数\n", n);
}
return 0;
}
// 默认num是正整数
int IsPrime(int num) {
if (num == 1) {
return 0; // 1不是质数
}
if (num == 2) {
return 1; // 2是质数
} else {
// 除以比自己小的质数
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)