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


window 1, @"Primality By Trial Division", (0,0,480,270)
 
local fn isPrime( n as long ) as Boolean
  long    i
  Boolean result
 
  if n < 2 then result = NO : exit fn
  if n = 2 then result = YES : exit fn
  if n mod 2 == 0  then result = NO : exit fn
 
  result = YES
  for i = 3 to int( n^.5 ) step 2
    if n mod i == 0 then result = NO : break
  next i
end fn = result
 
long i, j = 0
 
print "Prime numbers between 0 and 1000:"
for i = 0 to 1000
  if ( fn isPrime(i) != _false )
    printf @"%3d\t",i : j++
    if j mod 10 == 0 then print
  end if
next
 
HandleEvents