;;; math-fns.el --- various mathematic functions for emacs

;; Author: Noah Friedman <friedman@splode.com>
;; Maintainer: friedman@splode.com
;; Public domain.

;; $Id: math-fns.el,v 1.1 1999/10/10 18:58:00 friedman Exp $

;;; Commentary:
;;; Code:

;;;###autoload
(defun next-power-of-two (x)
  "Returns the smallest power of two greater than X."
  (lsh 1 (1+ (logb x))))

;;;###autoload
(defun greatest-common-divisor (a b)
  "Return the greatest integer that divides both A and B."
  (let ((result 0)
        min max)
    (cond ((and (zerop a) (zerop b)))
          (t
           (while (zerop result)
             (setq min (min a b))
             (setq max (max a b))
             (if (zerop (% max min))
                 (setq result min)
               (setq max (- max min))
               (setq a max)
               (setq b min)))))
    result))

;;;###autoload
(defun least-common-multiple (a b)
  "Return the smallest number which has both A and B as factors."
  (* (/ (max a b)
        (greatest-common-divisor a b))
     (min a b)))

;;;###autoload
(defun valbits (&optional n)
  "Returns the number of binary bits required to represent n.
If n is not specified, this is effectively the number of valbits emacs uses
to represent ints---including the sign bit.

Negative values of n will always require VALBITS bits, the number of bits
emacs actually uses for its integer values, since the highest bit is used
for the sign; use (abs n) to ignore the sign."
  (or n (setq n -1))
  (let ((b 0))
    (while (not (zerop n))
      (setq n (lsh n -1))
      (setq b (1+ b)))
    b))

(provide 'math-fns)

;;; math-fns.el ends here.
