fr1kin

findPrimes (sieve of Atkin)

Apr 13th, 2014
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.92 KB | None | 0 0
  1. local function findPrimes(range)
  2.     local lim, num, j;
  3.     local is_prime = {};
  4.     is_prime[2] = true;
  5.     is_prime[3] = true;
  6.     for i = 5, range do
  7.         is_prime[i] = false;
  8.     end
  9.     local lim = math.ceil(math.sqrt(range));
  10.     for x = 1, lim do
  11.         for y = 1, lim do
  12.             num = (4 * x^2 + y^2);
  13.             if(num <= range and (num % 12 == 1 or num % 12 == 5)) then
  14.                 is_prime[num] = true;
  15.             end
  16.             num = (3 * x^2 + y^2);
  17.             if(num <= range and (num % 12 == 7)) then
  18.                 is_prime[num] = true;
  19.             end
  20.             if(x > y) then
  21.                 num = (3 * x^2 - y^2);
  22.                 if(num <= range and (num % 12 == 11)) then
  23.                     is_prime[num] = true;
  24.                 end
  25.             end
  26.         end
  27.     end
  28.     for i = 5, lim do
  29.         if(is_prime[i]) then
  30.             j = i^2;
  31.             while(j <= range) do
  32.                 is_prime[j] = false;
  33.                 j = j + i;
  34.             end
  35.         end
  36.     end
  37.     local primes = {};
  38.     for i = 2, range do
  39.         if(is_prime[i]) then
  40.             table.insert(primes, i);
  41.         end
  42.     end
  43.     table.sort(primes);
  44.     return primes;
  45. end
Advertisement
Add Comment
Please, Sign In to add comment