Task

Write a boolean function that tells whether a given integer is prime.



Remember that   1   and all non-positive numbers are not prime.

Use trial division.

Even numbers greater than   2   may be eliminated right away.

A loop from   3   to   √ n    will suffice,   but other loops are allowed.



Related tasks

   count in factors
   prime decomposition
   AKS test for primes
   factors of an integer
   Sieve of Eratosthenes
   factors of a Mersenne number
   trial factoring of a Mersenne number
   partition an integer X into N primes
   sequence of primes by Trial Division


 
$lines
 
$constant FALSE = 0
$constant TRUE = 0FFFFH
 
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
 
rem - return true (-1) if n is prime, otherwise false (0)
function isprime(n = integer) = integer
  var i, limit, result = integer
  if n = 2 then
    result = TRUE
  else if (n < 2) or (mod(n,2) = 0) then
    result = FALSE
  else 
    begin
      limit = int(sqr(n))
      i = 3
      while (i <= limit) and (mod(n, i) <> 0) do
        i = i + 2
      result = not (i <= limit)
    end
end = result
 
rem - test by looking for primes in range 1 to 50
var i = integer
for i = 1 to 50 
  if isprime(i) then print using "#####";i;
next i
 
end
 