-2

my teacher gave me this :

n<=10^6;

an array of n integer :ai..an(ai<=10^9);

find all prime numbers .

he said something about sieve of eratosthenes,and I read about it,also the wheel factorization too,but I still couldn't figure it out how to get the program (fpc) to run in 1s.?? as I know it's impossible,but still want to know your opinion . and with the wheel factorization ,a 2*3 circle will treat 25 as a prime number,and I wanna ask if there is a way to find out the first number of the wheel treated wrong as a prime number. example:2*3*5 circle ,how to find the first composite number treated as aprime number?? please help..and sorry for bad english.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • Have a look at [Wikipedia](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) there's also a sample implementaion of the sieve. This is easier than the wheel. – joe Oct 08 '14 at 05:26
  • Free Pascal comes with a basic sieve example in demo/text/eratos.pp The wheel factorization is probably the key of the assignment. Showing what you already have would make it easier to comment. – Marco van de Voort Oct 08 '14 at 12:20

2 Answers2

1

A proper Sieve of Eratosthenes should find the primes less than a billion in about a second; it's possible. If you show us your code, we'll be happy to help you find what is wrong.

The smallest composite not marked by a 2,3,5-wheel is 49: the next largest prime not a member of the wheel is 7, and 7 * 7 = 49.

user448810
  • 17,381
  • 4
  • 34
  • 59
0

I did it now and it's finding primes up to 1000000 in a few milliseconds, without displaying all those numbers. Declare an array a of n + 1 bools (if it is zero-based). At the beginning 0th and 1st element are false, all others are true (false is not a prime). The algorithm looks like that:

i = 2;
while i * i <= n
    if a[i] == true
        j = i * i;
        while j < n
            a[j] = false;
            j = j + i;
    i = i + 1;

In a loop the condition is i * i <= n because you start searching from i * i (smaller primes than that was found already by one of other primes) so square root of i must not be bigger than n. You remove all numbers which are multiplies of primes up to n. Time complexity is O(n log log n). If you want to display primes, you display indexes which values in array are true.

Factorization is usefull if you want to find e.g. all semiprimes from 0 to n (products of two prime numbers). Then you find all smallest prime divisors from 0 to n/2 and check for each number if it has prime divisor and if number divided by its prime divisor has zero divisors. If so - it is a semiprime. My program wrote like that was calculating 8 times faster than first finding all primes and then multiplying them and saving result in an array.

alcohol is evil
  • 686
  • 12
  • 34