Which is the fastest algorithm to find prime numbers?

后端 未结 14 1386
情深已故
情深已故 2020-11-22 06:49

Which is the fastest algorithm to find out prime numbers using C++? I have used sieve\'s algorithm but I still want it to be faster!

14条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:03

    i wrote it today in C,compiled with tcc, figured out during preparation of compititive exams several years back. don't know if anyone already have wrote it alredy. it really fast(but you should decide whether it is fast or not). took one or two minuts to findout about 1,00,004 prime numbers between 10 and 1,00,00,000 on i7 processor with average 32% CPU use. as you know, only those can be prime which have last digit either 1,3,7 or 9 and to check if that number is prime or not, you have to divide that number by previously found prime numbers only. so first take group of four number = {1,3,7,9}, test it by dividing by known prime numbers, if reminder is non zero then number is prime, add it to prime number array. then add 10 to group so it becomes {11,13,17,19} and repeat the process.

    #include 
    int main() {    
        int nums[4]={1,3,7,9};
        int primes[100000];
        primes[0]=2;
        primes[1]=3;
        primes[2]=5;
        primes[3]=7;
        int found = 4;
        int got = 1;
        int m=0;
        int upto = 1000000;
        for(int i=0;i

提交回复
热议问题