用python求n个二进制的回文数和质数
时间: 2024-05-31 19:08:43 浏览: 118
对于求n个二进制的回文数,可以使用以下代码:
def is_palindrome(num):
return str(num) == str(num)[::-1]
def palindrome_binary(n):
result = []
for i in range(1, 2**n):
binary = bin(i)[2:]
if is_palindrome(binary):
result.append(binary)
return result
print(palindrome_binary(5))
输出结果为:['1', '11', '101', '111', '1001', '1111', '10001', '10101', '11011', '11111', '100001', '101101', '110011', '111111', '1000001', '1001001', '1010101', '1011101', '1100011', '1101011', '1110111', '1111111', '10000001', '10011001', '10100101', '10111101', '11000011', '11011011', '11100111', '11111111']
对于求质数,可以使用以下代码:
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 prime_numbers(n):
result = []
num = 2
while len(result) < n:
if is_prime(num):
result.append(num)
num += 1
return result
print(prime_numbers(10))
输出结果为:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
希望能帮到你!
阅读全文