Elisp factorial calculation gives incorrect result

If I write this function in emacs-lisp:

(defun factorial (n)
  (if (<= n 1)
      1
      (* n (factorial (- n 1)))))
      => factorial

This works well for small numbers, such as 5 or 10, but if I try to calculate (factor 33), the answer will be -1211487723752259584, which is obviously not true, all large numbers violate the function. In python this does not happen. What causes this problem?

+5
source share
3 answers

Integers have a certain range . Values ​​outside this range cannot be represented. This is pretty standard for most programming languages, but not for everyone. You can find the largest number of Emacs Lisp integer data types that can be processed on your computer by checking the value most-positive-fixnum.

*scratch* Lisp most-positive-fixnum. , C-x C-e. 2305843009213693951. , : 64- , 2^61. 33 8683317618811886495518194401280000000. 2 ^ 86, , Emacs. ( Arc, , Arc , , ).

+11

Emacs calc .

(defun factorial (n)
  (string-to-number (factorial--1 n)))

(defun factorial--1 (n)
  (if (<= n 1)
      "1"
    (calc-eval (format "%s * %s"
                       (number-to-string n)
                       (factorial--1 (- n 1))))))


ELISP> (factorial 33)  
8.683317618811886e+036

:

+12

:

(defun factorial (n) (calc-eval (format "%s!" n)))

ELISP> (factorial 33)
8683317618811886495518194401280000000

, , Calc, calc-eval string. Emacs Lisp Calc .

Calc defmathand functions are calcFunc-so powerful in Emacs Lisp.

(defmath myFact (n) (string-to-number (format-number (calcFunc-fact n))))

ELISP> (calcFunc-myFact 33)
8.683317618811886e+36
+4
source

All Articles