埃拉托色尼筛选法:
(1)先把1删除(现今数学界1既不是质数也不是合数)
(2)读取队列中当前最小的数2,然后把2的倍数删去
(3)读取队列中当前最小的数3,然后把3的倍数删去
(4)读取队列中当前最小的数5,然后把5的倍数删去
(5)读取队列中当前最小的数7,然后把7的倍数删去
(6)如上所述直到需求的范围内所有的数均删除或读取
** python编程 **
def _int_iter(): #生成器生成从3开始的无限奇数序列
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n): #定义筛选函数
return lambda x:x % n > 0
def primes():
yield 2 #先返回一个2
it = _int_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
for n in primes(): #构造循环条件,使之可以输出任何范围的素数序列
if n < 1000:
print(n)
else:
break
回数是指从左向右读和从右向左读都是一样的数
python程序:
def is_palindrome(n):
n=str(n)
while n[::-1]==n:
return int(n)
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
>>>1~1000: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]