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


' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
  If n < 2 Then Return False
  If n = 2 Then Return True
  If n Mod 2  = 0 Then Return False
  Dim limit As Integer = Sqr(n)
  For i As Integer = 3 To limit Step 2
    If n Mod i = 0 Then Return False
  Next
  Return True
End Function
 
' To test this works, print all primes under 100
For i As Integer = 1 To 99
  If isPrime(i) Then 
    Print Str(i); " "; 
  End If
Next
 
Print : Print
Print "Press any key to quit"
Sleep