Strong and weak primes: Difference between revisions

Content added Content deleted
(Added Perl example)
(Added Lua version)
Line 138: Line 138:


The number of weak primes below 10,000,000 is 321,750
The number of weak primes below 10,000,000 is 321,750
</pre>

=={{header|Lua}}==
This could be made faster but favours readability. It runs in about 3.3 seconds in LuaJIT on a 2.8 GHz core.
<lang lua>-- Return a table of the primes up to n, then one more
function primeList (n)
local function isPrime (x)
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local pTable, j = {2, 3}
for i = 5, n, 2 do
if isPrime(i) then
table.insert(pTable, i)
end
j = i
end
repeat j = j + 1 until isPrime(j)
table.insert(pTable, j)
return pTable
end

-- Return a boolean indicating whether prime p is strong
function isStrong (p)
if p == 1 or p == #prime then return false end
return prime[p] > (prime[p-1] + prime[p+1]) / 2
end

-- Return a boolean indicating whether prime p is weak
function isWeak (p)
if p == 1 or p == #prime then return false end
return prime[p] < (prime[p-1] + prime[p+1]) / 2
end

-- Main procedure
prime = primeList(1e7)
local strong, weak, sCount, wCount = {}, {}, 0, 0
for k, v in pairs(prime) do
if isStrong(k) then
table.insert(strong, v)
if v < 1e6 then sCount = sCount + 1 end
end
if isWeak(k) then
table.insert(weak, v)
if v < 1e6 then wCount = wCount + 1 end
end
end
print("The first 36 strong primes are:")
for i = 1, 36 do io.write(strong[i] .. " ") end
print("\n\nThere are " .. sCount .. " strong primes below one million.")
print("\nThere are " .. #strong .. " strong primes below ten million.")
print("\nThe first 37 weak primes are:")
for i = 1, 37 do io.write(weak[i] .. " ") end
print("\n\nThere are " .. wCount .. " weak primes below one million.")
print("\nThere are " .. #weak .. " weak primes below one million.")</lang>
{{out}}
<pre>The first 36 strong primes are:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439

There are 37723 strong primes below one million

There are 320991 strong primes below ten million

The first 37 weak primes are:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401

There are 37780 weak primes below one million

There are 321750 weak primes below one million
</pre>
</pre>