---
title: Math functions
description: Simple mathematical Scheme functions.
group: Examples
order: 1
---

Below are a few mathematical functions for computing the factorial decomposition of an integer, for
determining whether a number is a prime number as well as for computing the factorial and the n-th
fibonacci number.

{% highlight scheme %}
;; Returns the factorial decomposition of integer `n` in form of a list of prime numbers
(define (factors n)
  (cond ((negative? n) (cons -1 (factors (- n))))
        ((< n 3)       (list n))
        ((even? n)     (cons 2 (factors (/ n 2))))
        (else          (let loop ((divisor 3) (n n))
                         (if (> (square divisor) n)
                             (list n)
                             (if (zero? (modulo n divisor))
                                 (cons divisor (loop divisor (/ n divisor)))
                                 (loop (+ divisor 2) n)))))))

;; Returns `#t` if integer `n` is a prime number, `#f` otherwise.
(define (prime? n)
  (cond ((= n 0)   #f)
        ((= n 1)   #f)
        ((= n 2)   #t)
        ((even? n) #f)
        (else      (let loop ((d 3))
                     (cond ((> (square d) n)        #t)
                           ((zero? (remainder n d)) #f)
                           (else                    (loop (+ d 2))))))))

;; Returns the `n`-th Fibonacci number
(define (fib n)
  (if (fx< n 2)
      n
      (fx+ (fib (fx1- n)) (fib (fx- n 2)))))

;; Returns the factorial of integer `n`
(define (fac n)
  (if (= n 0)
      1
      (* n (fac (- n 1)))))
{% endhighlight %}
