How to resolve the algorithm Primality by trial division step by step in the Ol programming language

Published on 12 May 2024 09:40 PM
#Ol

How to resolve the algorithm Primality by trial division step by step in the Ol programming language

Table of Contents

Problem Statement

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.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Primality by trial division step by step in the Ol programming language

Source code in the ol programming language

(define (prime? number)
   (define max (sqrt number))
   (define (loop divisor)
      (or (> divisor max)
          (and (> (modulo number divisor) 0)
               (loop (+ divisor 2)))))
   (or (= number 1)
       (= number 2)
       (and
          (> (modulo number 2) 0)
          (loop 3))))


; first prime numbers less than 100
(for-each (lambda (n)
      (if (prime? n)
         (display n))
      (display " "))
   (iota 100))
(print)

; few more sintetic tests
(for-each (lambda (n)
      (print n " - prime? " (prime? n)))
   '(
      1234567654321 ; 1111111 * 1111111
      679390005787 ; really prime, I know that
      679390008337 ; same
      666810024403 ; 680633 * 979691 (multiplication of two prime numbers)
      12345676543211234567654321
      12345676543211234567654321123456765432112345676543211234567654321123456765432112345676543211234567654321
   ))


  

You may also check:How to resolve the algorithm Halt and catch fire step by step in the C programming language
You may also check:How to resolve the algorithm Even or odd step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the Lua programming language
You may also check:How to resolve the algorithm Circles of given radius through two points step by step in the Ruby programming language
You may also check:How to resolve the algorithm Combinations step by step in the Clojure programming language