Skip to content

Instantly share code, notes, and snippets.

@hawx
Created February 5, 2015 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hawx/d27877f6b005db7ccce0 to your computer and use it in GitHub Desktop.
Save hawx/d27877f6b005db7ccce0 to your computer and use it in GitHub Desktop.
Old maths homework solving
#!/usr/bin/env newlisp
;; Prints the nth fibonacci number
(define (fib n)
(if (< n 2)
1
(+ (fib (- n 1))
(fib (- n 2)))))
;; Solves equations of the form
;; ax + by = gcd(a, b)
;; returns (x y).
(define (ext-gcd a b)
(if (zero? b) '(1 0)
(let (q (/ a b))
(let (r (- a (* b q)))
(let (s (ext-gcd b r))
(list (last s) (- (first s) (* q (last s)))))))))
;; Solves a diphantine equqtion of the form
;; a(x + dk) + b(y + ek) = c, for some int k
;; returns a list corresponding to (d e x y).
(define (diophantine a b c)
(letn (h (gcd a b)
ss (ext-gcd a b)
s (first ss) t (last ss)
x (* s (/ c h))
y (* t (/ c h))
d (/ b h)
e (/ a h))
(list d e x y)))
;; Print the general solution to a diophantine equation
(define (gen-diophantine a b c)
(let (di (diophantine a b c))
(format "%d * (%d + %dk) + %d * (%d - %dk) = %d"
(list a (nth 2 di) (nth 0 di)
b (nth 3 di) (nth 1 di)
c))))
;; Print a particular solution to a diophantine equation
(define (par-diophantine a b c)
(let (di (diophantine a b c))
(format "%d * %d + %d * %d = %d"
(list a (nth 2 di)
b (nth 3 di)
c))))
(println "
MATHS REPL
----------
(gcd a b) -- calculates gcd of a and b
(gen-diophantine a b c) -- prints general solution to diophantine eq.
(par-diophantine a b c) -- prints a particular solution to diophantine eq.
")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment