Browse Source

Added mod-arithmatic.lisp

Samuel W. Flint 8 years ago
parent
commit
6381bd163b
1 changed files with 65 additions and 0 deletions
  1. 65 0
      mod-arithmatic.lisp

+ 65 - 0
mod-arithmatic.lisp

@@ -0,0 +1,65 @@
+;;;; modular-arithmatic-tables.lisp
+;;;;
+;;;; Copyright (c) 2016 Samuel W. Flint <swflint@flintfam.org>
+
+(defpackage #:mod-arithmatic
+  (:use #:cl)
+  (:export :print-tables-z_n
+           :make-z_n-tables))
+
+
+(in-package #:mod-arithmatic)
+
+;;; "mod-arithmatic" goes here.
+
+(defun euclid-gcd (a b)
+  (check-type a integer)
+  (check-type b integer)
+  (cond
+    ((zerop b)
+     a)
+    ((= a b)
+     a)
+    ((< a b)
+     (euclid-gcd b a))
+    (t
+     (euclid-gcd b (mod a b)))))
+
+(defun z_n-divisors (n)
+  (remove-if (lambda (x)
+               (not (= 1 (euclid-gcd x n))))
+             (loop for i from 1 to (1- n) collect i)))
+
+(defun z_n-addition-table (n)
+  (loop for i from 0 to (1- n)
+     collect (loop for j from 0 to (1- n)
+                collect (mod (+ i j) n))))
+
+(defun z_n-multiplication-table (n)
+  (loop for i from 0 to (1- n)
+     collect (loop for j from 0 to (1- n)
+                collect (mod (* i j) n))))
+
+(defun print-z_n-addition-table (n stream)
+  (format stream "~{~{~4d~}~&~}" (z_n-addition-table n)))
+
+(defun print-z_n-multiplication-table (n stream)
+  (format stream "~{~{~4d~}~&~}" (z_n-multiplication-table n)))
+
+(defun print-tables-z_n (n stream)
+  (check-type n integer)
+  (format stream "Addition Table (Z_~d):~%" n)
+  (print-z_n-addition-table n stream)
+  (format stream "~&~%Multiplication Table (Z_~d):~%" n)
+  (print-z_n-multiplication-table n stream)
+  (format stream "~&~%Divisors in Z_~d:~&" n)
+  (format stream "~{~a~^, ~}" (z_n-divisors n)))
+
+(defun make-z_n-tables (n filename)
+  (with-open-file (output filename
+                          :direction :output
+                          :if-exists :overwrite
+                          :if-does-not-exist :create)
+    (print-tables-z_n n output)))
+
+;;; End mod-arithmatic