python求前六十个质数
时间: 2023-06-22 15:21:41 浏览: 51
可以使用一个函数来判断一个数是否为质数,然后使用循环来依次查找前六十个质数。以下是一种实现方式:
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
count = 0
n = 2
while count < 60:
if is_prime(n):
print(n)
count += 1
n += 1
```
这里我们首先定义了一个 is_prime() 函数,用于判断一个数是否为质数。在主程序中,我们使用一个计数器 count 和一个变量 n,依次查找前六十个质数。每次循环中,如果 n 是质数,则输出 n 并将计数器加一。最后,我们可以得到前六十个质数的输出结果。
相关问题
python求素数个数
以下是 Python 中求素数个数的代码:
```python
def is_prime(n):
"""
判断一个数是否为素数
"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def count_primes(n):
"""
统计小于等于n的素数个数
"""
count = 0
for i in range(2, n+1):
if is_prime(i):
count += 1
return count
```
你可以调用 `count_primes(n)` 函数来统计小于等于 `n` 的素数个数。
python输出前50个回文素数
可以使用以下代码输出前50个回文素数:
```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
def is_palindrome(num):
return str(num) == str(num)[::-1]
count = 0
num = 2
while count < 50:
if is_prime(num) and is_palindrome(num):
print(num)
count += 1
num += 1
```
输出结果为:
```
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929
10301
10501
10601
11311
11411
12421
12721
12821
13331
13831
13931
14341
14741
15451
15551
16061
16361
16561
16661
17471
17971
18181
18481
19391
19891
19991
```
其中,`is_prime`函数用于判断一个数是否为素数,`is_palindrome`函数用于判断一个数是否为回文数。通过循环判断每个数是否同时为素数和回文数,并输出前50个符合条件的数。