定义一个 prime() 函数求整数 n 以内(不包括n)的所有素数(1不是素数),并返回一个按照升序排列的素数列表。使用递归来实现一个二分查找算法函数bi_search(),该函数实现检索任意一个整数在 prime() 函数生成的素数列表中位置(索引)的功能,并返回该位置的索引值,若该数不存在则返回 -1。
输入格式:
第一行为正整数 n
接下来若干行为待查找的数字,每行输入一个数字
输出格式:
每行输出相应的待查找数字的索引值
输入样例:
10
2
4
6
7
输出样例:
0
-1
-1
3
时间限制:500ms内存限制:32000kb
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import re
# import itertools
import math
# import datetime
# import sys
# from PyQt4.QtCore import *
# from PyQt4.QtGui import *
# import numpy as np
# import matplotlib.pyplot as plt
# import copy
def primeindex(n):
l = []
def is_prime(n):
for i in xrange(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
for i in xrange(2, n):
if is_prime(i):
l.append(i)
return l
def bi_search(lst, low, high, x):
while low <= high:
mid = (low + high) / 2
if lst[mid] == x:
return mid
elif lst[mid] > x:
return bi_search(lst, low, mid - 1, x)
else:
return bi_search(lst, low + 1, high, x)
return -1
if __name__ == '__main__':
n = int(raw_input())
lp = primeindex(n)
high = len(lp) - 1
l = []
while True:
num = raw_input()
if num == '':
break
else:
l.append(int(num))
for i in l:
print bi_search(lp, 0, high, i)