计算第K个素数
发布日期:2021-08-15 22:29:19 浏览次数:33 分类:技术文章

本文共 2413 字,大约阅读时间需要 8 分钟。

暂时没有时间整理,先放在这里:

http://www.quora.com/Prime-Numbers/What-are-good-ways-to-find-nth-prime-number-in-the-fastest-way

—————————————————————————————————————————————————————————————————————

This is an algorithm to test whether or not a given integer is prime. It's called the AKS primality test

And can be done in polynomial time, which is usually considered a decent amount of time.
Now if you're trying to compute the nth prime, it has been proven that the nth prime must be greater than
n \ln(n) + n(\ln(\ln(n)) - 1)
and less than
n \ln(n) + n \ln(\ln(n))
When n \ge 6. So if you're searching for the nth prime, I'd look in this gap.

——————————————————————————————————————————————————————————————————————

If it is an interview question, I believe Sieve of Eratosthenes algorithm is a pretty good answer. For not too large n, the algorithm should work fine. For extremely large n, then you probably have to use a precomputed array of bins. Each covers a range of [i*N-i*(N+1)-1] and the number of prime numbers in that range as described in [2].
There is no general formula to compute nth prime number.
[1]
[2]
  

—————————————————————————————————————————————————————————————————————

附上一个同学写的用bitarray实现的求素数的方法:

/* * ======================================================================== * *       Filename:  bitset.h * *    Description:  bitset implementation in c. * *        Created:  05/27/2013 11:09:43 PM * *         Author:  Fu Haiping (forhappy), haipingf@gmail.com *        Company:  ICT ( Institute Of Computing Technology, CAS ) * * ======================================================================== */#include 
/* for CHAR_BIT */#define BITMASK(b) (1 << ((b) % CHAR_BIT))#define BITSLOT(b) ((b) / CHAR_BIT)#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)/* * char bitarray[BITNSLOTS(47)]; * BITSET(bitarray, 23); * if(BITTEST(bitarray, 35)) ... * * */#include
#include
#define MAX 10000int main(){ char bitarray[BITNSLOTS(MAX)]; int i, j; memset(bitarray, 0, BITNSLOTS(MAX)); for(i = 2; i < MAX; i++) { if(!BITTEST(bitarray, i)) { printf("%d\n", i); for(j = i + i; j < MAX; j += i) BITSET(bitarray, j); } } return 0;}

 

 

 

转载于:https://www.cnblogs.com/avril/p/3175537.html

转载地址:https://blog.csdn.net/weixin_30781107/article/details/97088907 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:xgboost学习
下一篇:hdu3917 最大权闭合图

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月09日 17时50分38秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章