Chinaunix首页 | 论坛 | 博客
  • 博客访问: 86671
  • 博文数量: 47
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 625
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-11 12:11
文章分类

全部博文(47)

文章存档

2008年(47)

我的朋友

分类:

2008-11-12 11:06:16

Problem 7

28 December 2001

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

def fun7():
  primes = [2]
  cnt    = 1
  i      = 3
  isPrime=True
  while cnt < 10001:
    isPrime = True
    for j in primes:
      if i%j == 0:
        i+=2
        isPrime = False
        break
    if not isPrime:
      continue

    primes.append(i)
    i   += 2
    cnt += 1
  print i-2, cnt

answer is 104743

速度有点慢,用了9秒。在判断是否为素数时

def fun7():
  primes = [2]
  cnt    = 1
  i      = 3
  isPrime=True
  while cnt < 10001:
    isPrime = True
    temp = math.sqrt(i)
    for j in primes:
      if j > temp:
        break

      if (i%j == 0):
        i+=2
        isPrime = False
        break
    if not isPrime:
      continue

    primes.append(i)
    i   += 2
    cnt += 1
  print i-2, cnt

代码运行时间可以缩短为0.296999931335

阅读(402) | 评论(0) | 转发(0) |
0

上一篇:Problem 5

下一篇:Problem 8

给主人留下些什么吧!~~