Initial Commit
[packages] / xemacs-packages / calc / calc-comb.el
1 ;; Calculator for GNU Emacs, part II [calc-comb.el]
2 ;; Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
3 ;; Written by Dave Gillespie, daveg@synaptics.com.
4
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is distributed in the hope that it will be useful,
8 ;; but WITHOUT ANY WARRANTY.  No author or distributor
9 ;; accepts responsibility to anyone for the consequences of using it
10 ;; or for whether it serves any particular purpose or works at all,
11 ;; unless he says so in writing.  Refer to the GNU Emacs General Public
12 ;; License for full details.
13
14 ;; Everyone is granted permission to copy, modify and redistribute
15 ;; GNU Emacs, but only under the conditions described in the
16 ;; GNU Emacs General Public License.   A copy of this license is
17 ;; supposed to have been given to you along with GNU Emacs so you
18 ;; can know your rights and responsibilities.  It should be in a
19 ;; file named COPYING.  Among other things, the copyright notice
20 ;; and this notice must be preserved on all copies.
21
22
23
24 ;; This file is autoloaded from calc-ext.el.
25 (require 'calc-ext)
26
27 (require 'calc-macs)
28
29 (defun calc-Need-calc-comb () nil)
30
31
32 ;;; Combinatorics
33
34 (defun calc-gcd (arg)
35   (interactive "P")
36   (calc-slow-wrapper
37    (calc-binary-op "gcd" 'calcFunc-gcd arg))
38 )
39
40 (defun calc-lcm (arg)
41   (interactive "P")
42   (calc-slow-wrapper
43    (calc-binary-op "lcm" 'calcFunc-lcm arg))
44 )
45
46 (defun calc-extended-gcd ()
47   (interactive)
48   (calc-slow-wrapper
49    (calc-enter-result 2 "egcd" (cons 'calcFunc-egcd (calc-top-list-n 2))))
50 )
51
52 (defun calc-factorial (arg)
53   (interactive "P")
54   (calc-slow-wrapper
55    (calc-unary-op "fact" 'calcFunc-fact arg))
56 )
57
58 (defun calc-gamma (arg)
59   (interactive "P")
60   (calc-slow-wrapper
61    (calc-unary-op "gmma" 'calcFunc-gamma arg))
62 )
63
64 (defun calc-double-factorial (arg)
65   (interactive "P")
66   (calc-slow-wrapper
67    (calc-unary-op "dfac" 'calcFunc-dfact arg))
68 )
69
70 (defun calc-choose (arg)
71   (interactive "P")
72   (calc-slow-wrapper
73    (if (calc-is-hyperbolic)
74        (calc-binary-op "perm" 'calcFunc-perm arg)
75      (calc-binary-op "chos" 'calcFunc-choose arg)))
76 )
77
78 (defun calc-perm (arg)
79   (interactive "P")
80   (calc-hyperbolic-func)
81   (calc-choose arg)
82 )
83
84 (defvar calc-last-random-limit '(float 1 0))
85 (defun calc-random (n)
86   (interactive "P")
87   (calc-slow-wrapper
88    (if n
89        (calc-enter-result 0 "rand" (list 'calcFunc-random
90                                          (calc-get-random-limit
91                                           (prefix-numeric-value n))))
92      (calc-enter-result 1 "rand" (list 'calcFunc-random
93                                        (calc-get-random-limit
94                                         (calc-top-n 1))))))
95 )
96
97 (defun calc-get-random-limit (val)
98   (if (eq val 0)
99       calc-last-random-limit
100     (setq calc-last-random-limit val))
101 )
102
103 (defun calc-rrandom ()
104   (interactive)
105   (calc-slow-wrapper
106    (setq calc-last-random-limit '(float 1 0))
107    (calc-enter-result 0 "rand" (list 'calcFunc-random '(float 1 0))))
108 )
109
110 (defun calc-random-again (arg)
111   (interactive "p")
112   (calc-slow-wrapper
113    (while (>= (setq arg (1- arg)) 0)
114      (calc-enter-result 0 "rand" (list 'calcFunc-random
115                                        calc-last-random-limit))))
116 )
117
118 (defun calc-shuffle (n)
119   (interactive "P")
120   (calc-slow-wrapper
121    (if n
122        (calc-enter-result 1 "shuf" (list 'calcFunc-shuffle
123                                          (prefix-numeric-value n)
124                                          (calc-get-random-limit
125                                           (calc-top-n 1))))
126      (calc-enter-result 2 "shuf" (list 'calcFunc-shuffle
127                                        (calc-top-n 1)
128                                        (calc-get-random-limit
129                                         (calc-top-n 2))))))
130 )
131
132 (defun calc-report-prime-test (res)
133   (cond ((eq (car res) t)
134          (calc-record-message "prim" "Prime (guaranteed)"))
135         ((eq (car res) nil)
136          (if (cdr res)
137              (if (eq (nth 1 res) 'unknown)
138                  (calc-record-message
139                   "prim" "Non-prime (factors unknown)")
140                (calc-record-message
141                 "prim" "Non-prime (%s is a factor)"
142                 (math-format-number (nth 1 res))))
143            (calc-record-message "prim" "Non-prime")))
144         (t
145          (calc-record-message
146           "prim" "Probably prime (%d iters; %s%% chance of error)"
147           (nth 1 res)
148           (let ((calc-float-format '(fix 2)))
149             (math-format-number (nth 2 res))))))
150 )
151
152 (defun calc-prime-test (iters)
153   (interactive "p")
154   (calc-slow-wrapper
155    (let* ((n (calc-top-n 1))
156           (res (math-prime-test n iters)))
157      (calc-report-prime-test res)))
158 )
159
160 (defun calc-next-prime (iters)
161   (interactive "p")
162   (calc-slow-wrapper
163    (let ((calc-verbose-nextprime t))
164      (if (calc-is-inverse)
165          (calc-enter-result 1 "prvp" (list 'calcFunc-prevprime
166                                            (calc-top-n 1) (math-abs iters)))
167        (calc-enter-result 1 "nxtp" (list 'calcFunc-nextprime
168                                          (calc-top-n 1) (math-abs iters))))))
169 )
170
171 (defun calc-prev-prime (iters)
172   (interactive "p")
173   (calc-invert-func)
174   (calc-next-prime iters)
175 )
176
177 (defun calc-prime-factors (iters)
178   (interactive "p")
179   (calc-slow-wrapper
180    (let ((res (calcFunc-prfac (calc-top-n 1))))
181      (if (not math-prime-factors-finished)
182          (calc-record-message "pfac" "Warning:  May not be fully factored"))
183      (calc-enter-result 1 "pfac" res)))
184 )
185
186 (defun calc-totient (arg)
187   (interactive "P")
188   (calc-slow-wrapper
189    (calc-unary-op "phi" 'calcFunc-totient arg))
190 )
191
192 (defun calc-moebius (arg)
193   (interactive "P")
194   (calc-slow-wrapper
195    (calc-unary-op "mu" 'calcFunc-moebius arg))
196 )
197
198
199
200
201
202 (defun calcFunc-gcd (a b)
203   (if (Math-messy-integerp a)
204       (setq a (math-trunc a)))
205   (if (Math-messy-integerp b)
206       (setq b (math-trunc b)))
207   (cond ((and (Math-integerp a) (Math-integerp b))
208          (math-gcd a b))
209         ((Math-looks-negp a)
210          (calcFunc-gcd (math-neg a) b))
211         ((Math-looks-negp b)
212          (calcFunc-gcd a (math-neg b)))
213         ((Math-zerop a) b)
214         ((Math-zerop b) a)
215         ((and (Math-ratp a)
216               (Math-ratp b))
217          (math-make-frac (math-gcd (if (eq (car-safe a) 'frac) (nth 1 a) a)
218                                    (if (eq (car-safe b) 'frac) (nth 1 b) b))
219                          (calcFunc-lcm
220                           (if (eq (car-safe a) 'frac) (nth 2 a) 1)
221                           (if (eq (car-safe b) 'frac) (nth 2 b) 1))))
222         ((not (Math-integerp a))
223          (calc-record-why 'integerp a)
224          (list 'calcFunc-gcd a b))
225         (t
226          (calc-record-why 'integerp b)
227          (list 'calcFunc-gcd a b)))
228 )
229
230 (defun calcFunc-lcm (a b)
231   (let ((g (calcFunc-gcd a b)))
232     (if (Math-numberp g)
233         (math-div (math-mul a b) g)
234       (list 'calcFunc-lcm a b)))
235 )
236
237 (defun calcFunc-egcd (a b)   ; Knuth section 4.5.2
238   (cond
239    ((not (Math-integerp a))
240     (if (Math-messy-integerp a)
241         (calcFunc-egcd (math-trunc a) b)
242       (calc-record-why 'integerp a)
243       (list 'calcFunc-egcd a b)))
244    ((not (Math-integerp b))
245     (if (Math-messy-integerp b)
246         (calcFunc-egcd a (math-trunc b))
247       (calc-record-why 'integerp b)
248       (list 'calcFunc-egcd a b)))
249    (t
250     (let ((u1 1) (u2 0) (u3 a)
251           (v1 0) (v2 1) (v3 b)
252           t1 t2 q)
253       (while (not (eq v3 0))
254         (setq q (math-idivmod u3 v3)
255               t1 (math-sub u1 (math-mul v1 (car q)))
256               t2 (math-sub u2 (math-mul v2 (car q)))
257               u1 v1  u2 v2  u3 v3
258               v1 t1  v2 t2  v3 (cdr q)))
259       (list 'vec u3 u1 u2))))
260 )
261
262
263 ;;; Factorial and related functions.
264
265 (defun calcFunc-fact (n)   ; [I I] [F F] [Public]
266   (let (temp)
267     (cond ((Math-integer-negp n)
268            (if calc-infinite-mode
269                '(var uinf var-uinf)
270              (math-reject-arg n 'range)))
271           ((integerp n)
272            (if (<= n 20)
273                (aref '[1 1 2 6 24 120 720 5040 40320 362880
274                          (bigpos 800 628 3) (bigpos 800 916 39)
275                          (bigpos 600 1 479) (bigpos 800 20 227 6)
276                          (bigpos 200 291 178 87) (bigpos 0 368 674 307 1)
277                          (bigpos 0 888 789 922 20) (bigpos 0 96 428 687 355)
278                          (bigpos 0 728 705 373 402 6)
279                          (bigpos 0 832 408 100 645 121)
280                          (bigpos 0 640 176 8 902 432 2)] n)
281              (math-factorial-iter (1- n) 2 1)))
282           ((and (math-messy-integerp n)
283                 (Math-lessp n 100))
284            (math-inexact-result)
285            (setq temp (math-trunc n))
286            (if (>= temp 0)
287                (if (<= temp 20)
288                    (math-float (calcFunc-fact temp))
289                  (math-with-extra-prec 1
290                    (math-factorial-iter (1- temp) 2 '(float 1 0))))
291              (math-reject-arg n 'range)))
292           ((math-numberp n)
293            (let* ((q (math-quarter-integer n))
294                   (tn (and q (Math-lessp n 1000) (Math-lessp -1000 n)
295                            (1+ (math-floor n)))))
296              (cond ((and tn (= q 2)
297                          (or calc-symbolic-mode (< (math-abs tn) 20)))
298                     (let ((q (if (< tn 0)
299                                  (math-div
300                                   (math-pow -2 (- tn))
301                                   (math-double-factorial-iter (* -2 tn) 3 1 2))
302                                (math-div 
303                                 (math-double-factorial-iter (* 2 tn) 3 1 2)
304                                 (math-pow 2 tn)))))
305                       (math-mul q (if calc-symbolic-mode
306                                       (list 'calcFunc-sqrt '(var pi var-pi))
307                                     (math-sqrt-pi)))))
308                    ((and tn (>= tn 0) (< tn 20)
309                          (memq q '(1 3)))
310                     (math-inexact-result)
311                     (math-div
312                      (math-mul (math-double-factorial-iter (* 4 tn) q 1 4)
313                                (if (= q 1) (math-gamma-1q) (math-gamma-3q)))
314                      (math-pow 4 tn)))
315                    (t
316                     (math-inexact-result)
317                     (math-with-extra-prec 3
318                       (math-gammap1-raw (math-float n)))))))
319           ((equal n '(var inf var-inf)) n)
320           (t (calc-record-why 'numberp n)
321              (list 'calcFunc-fact n))))
322 )
323
324 (math-defcache math-gamma-1q nil
325   (math-with-extra-prec 3
326     (math-gammap1-raw '(float -75 -2))))
327
328 (math-defcache math-gamma-3q nil
329   (math-with-extra-prec 3
330     (math-gammap1-raw '(float -25 -2))))
331
332 (defun math-factorial-iter (count n f)
333   (if (= (% n 5) 1)
334       (math-working (format "factorial(%d)" (1- n)) f))
335   (if (> count 0)
336       (math-factorial-iter (1- count) (1+ n) (math-mul n f))
337     f)
338 )
339
340 (defun calcFunc-dfact (n)   ; [I I] [F F] [Public]
341   (cond ((Math-integer-negp n)
342          (if (math-oddp n)
343              (if (eq n -1)
344                  1
345                (math-div (if (eq (math-mod n 4) 3) 1 -1)
346                          (calcFunc-dfact (math-sub -2 n))))
347            (list 'calcFunc-dfact n)))
348         ((Math-zerop n) 1)
349         ((integerp n) (math-double-factorial-iter n (+ 2 (% n 2)) 1 2))
350         ((math-messy-integerp n)
351          (let ((temp (math-trunc n)))
352            (math-inexact-result)
353            (if (natnump temp)
354                (if (Math-lessp temp 200)
355                    (math-with-extra-prec 1
356                      (math-double-factorial-iter temp (+ 2 (% temp 2))
357                                                  '(float 1 0) 2))
358                  (let* ((half (math-div2 temp))
359                         (even (math-mul (math-pow 2 half)
360                                         (calcFunc-fact (math-float half)))))
361                    (if (math-evenp temp)
362                        even
363                      (math-div (calcFunc-fact n) even))))
364              (list 'calcFunc-dfact max))))
365         ((equal n '(var inf var-inf)) n)
366         (t (calc-record-why 'natnump n)
367            (list 'calcFunc-dfact n)))
368 )
369
370 (defun math-double-factorial-iter (max n f step)
371   (if (< (% n 12) step)
372       (math-working (format "dfact(%d)" (- n step)) f))
373   (if (<= n max)
374       (math-double-factorial-iter max (+ n step) (math-mul n f) step)
375     f)
376 )
377
378 (defun calcFunc-perm (n m)   ; [I I I] [F F F] [Public]
379   (cond ((and (integerp n) (integerp m) (<= m n) (>= m 0))
380          (math-factorial-iter m (1+ (- n m)) 1))
381         ((or (not (math-num-integerp n))
382              (and (math-messy-integerp n) (Math-lessp 100 n))
383              (not (math-num-integerp m))
384              (and (math-messy-integerp m) (Math-lessp 100 m)))
385          (or (math-realp n) (equal n '(var inf var-inf))
386              (math-reject-arg n 'realp))
387          (or (math-realp m) (equal m '(var inf var-inf))
388              (math-reject-arg m 'realp))
389          (and (math-num-integerp n) (math-negp n) (math-reject-arg n 'range))
390          (and (math-num-integerp m) (math-negp m) (math-reject-arg m 'range))
391          (math-div (calcFunc-fact n) (calcFunc-fact (math-sub n m))))
392         (t
393          (let ((tn (math-trunc n))
394                (tm (math-trunc m)))
395            (math-inexact-result)
396            (or (integerp tn) (math-reject-arg tn 'fixnump))
397            (or (integerp tm) (math-reject-arg tm 'fixnump))
398            (or (and (<= tm tn) (>= tm 0)) (math-reject-arg tm 'range))
399            (math-with-extra-prec 1
400              (math-factorial-iter tm (1+ (- tn tm)) '(float 1 0))))))
401 )
402
403 (defun calcFunc-choose (n m)   ; [I I I] [F F F] [Public]
404   (cond ((and (integerp n) (integerp m) (<= m n) (>= m 0))
405          (if (> m (/ n 2))
406              (math-choose-iter (- n m) n 1 1)
407            (math-choose-iter m n 1 1)))
408         ((not (math-realp n))
409          (math-reject-arg n 'realp))
410         ((not (math-realp m))
411          (math-reject-arg m 'realp))
412         ((not (math-num-integerp m))
413          (if (and (math-num-integerp n) (math-negp n))
414              (list 'calcFunc-choose n m)
415            (math-div (calcFunc-fact (math-float n))
416                      (math-mul (calcFunc-fact m)
417                                (calcFunc-fact (math-sub n m))))))
418         ((math-negp m) 0)
419         ((math-negp n)
420          (let ((val (calcFunc-choose (math-add (math-add n m) -1) m)))
421            (if (math-evenp (math-trunc m))
422                val
423              (math-neg val))))
424         ((and (math-num-integerp n)
425               (Math-lessp n m))
426          0)
427         (t
428          (math-inexact-result)
429          (let ((tm (math-trunc m)))
430            (or (integerp tm) (math-reject-arg tm 'fixnump))
431            (if (> tm 100)
432                (math-div (calcFunc-fact (math-float n))
433                          (math-mul (calcFunc-fact (math-float m))
434                                    (calcFunc-fact (math-float
435                                                    (math-sub n m)))))
436              (math-with-extra-prec 1
437                (math-choose-float-iter tm n 1 1))))))
438 )
439
440 (defun math-choose-iter (m n i c)
441   (if (and (= (% i 5) 1) (> i 5))
442       (math-working (format "choose(%d)" (1- i)) c))
443   (if (<= i m)
444       (math-choose-iter m (1- n) (1+ i)
445                         (math-quotient (math-mul c n) i))
446     c)
447 )
448
449 (defun math-choose-float-iter (count n i c)
450   (if (= (% i 5) 1)
451       (math-working (format "choose(%d)" (1- i)) c))
452   (if (> count 0)
453       (math-choose-float-iter (1- count) (math-sub n 1) (1+ i)
454                               (math-div (math-mul c n) i))
455     c)
456 )
457
458
459 ;;; Stirling numbers.
460
461 (defun calcFunc-stir1 (n m)
462   (math-stirling-number n m 1)
463 )
464
465 (defun calcFunc-stir2 (n m)
466   (math-stirling-number n m 0)
467 )
468
469 (defun math-stirling-number (n m k)
470   (or (math-num-natnump n) (math-reject-arg n 'natnump))
471   (or (math-num-natnump m) (math-reject-arg m 'natnump))
472   (if (consp n) (setq n (math-trunc n)))
473   (or (integerp n) (math-reject-arg n 'fixnump))
474   (if (consp m) (setq m (math-trunc m)))
475   (or (integerp m) (math-reject-arg m 'fixnump))
476   (if (< n m)
477       0
478     (let ((cache (aref math-stirling-cache k)))
479       (while (<= (length cache) n)
480         (let ((i (1- (length cache)))
481               row)
482           (setq cache (vconcat cache (make-vector (length cache) nil)))
483           (aset math-stirling-cache k cache)
484           (while (< (setq i (1+ i)) (length cache))
485             (aset cache i (setq row (make-vector (1+ i) nil)))
486             (aset row 0 0)
487             (aset row i 1))))
488       (if (= k 1)
489           (math-stirling-1 n m)
490         (math-stirling-2 n m))))
491 )
492 (setq math-stirling-cache (vector [[1]] [[1]]))
493
494 (defun math-stirling-1 (n m)
495   (or (aref (aref cache n) m)
496       (aset (aref cache n) m
497             (math-add (math-stirling-1 (1- n) (1- m))
498                       (math-mul (- 1 n) (math-stirling-1 (1- n) m)))))
499 )
500
501 (defun math-stirling-2 (n m)
502   (or (aref (aref cache n) m)
503       (aset (aref cache n) m
504             (math-add (math-stirling-2 (1- n) (1- m))
505                       (math-mul m (math-stirling-2 (1- n) m)))))
506 )
507
508
509 ;;; Produce a random 10-bit integer, with (random) if no seed provided,
510 ;;; or else with Numerical Recipes algorithm ran3 / Knuth 3.2.2-A.
511 (defun math-init-random-base ()
512   (if (and (boundp 'var-RandSeed) var-RandSeed)
513       (if (eq (car-safe var-RandSeed) 'vec)
514           nil
515         (if (Math-integerp var-RandSeed)
516             (let* ((seed (math-sub 161803 var-RandSeed))
517                    (mj (1+ (math-mod seed '(bigpos 0 0 1))))
518                    (mk (1+ (math-mod (math-quotient seed '(bigpos 0 0 1))
519                                      '(bigpos 0 0 1))))
520                    (i 0))
521               (setq math-random-table (cons 'vec (make-list 55 mj)))
522               (while (<= (setq i (1+ i)) 54)
523                 (let* ((ii (% (* i 21) 55))
524                        (p (nthcdr ii math-random-table)))
525                   (setcar p mk)
526                   (setq mk (- mj mk)
527                         mj (car p)))))
528           (math-reject-arg var-RandSeed "*RandSeed must be an integer"))
529         (setq var-RandSeed (list 'vec var-RandSeed)
530               math-random-ptr1 math-random-table
531               math-random-cache nil
532               math-random-ptr2 (nthcdr 31 math-random-table))
533         (let ((i 200))
534           (while (> (setq i (1- i)) 0)
535             (math-random-base))))
536     (random t)
537     (setq var-RandSeed nil
538           math-random-cache nil
539           i 0
540           math-random-shift -4)  ; assume RAND_MAX >= 16383
541     ;; This exercises the random number generator and also helps
542     ;; deduce a better value for RAND_MAX.
543     (while (< (setq i (1+ i)) 30)
544       (if (> (lsh (math-abs (random)) math-random-shift) 4095)
545           (setq math-random-shift (1- math-random-shift)))))
546   (setq math-last-RandSeed var-RandSeed
547         math-gaussian-cache nil)
548 )
549
550 (defun math-random-base ()
551   (if var-RandSeed
552       (progn
553         (setq math-random-ptr1 (or (cdr math-random-ptr1)
554                                    (cdr math-random-table))
555               math-random-ptr2 (or (cdr math-random-ptr2)
556                                    (cdr math-random-table)))
557         (logand (lsh (setcar math-random-ptr1
558                              (logand (- (car math-random-ptr1)
559                                         (car math-random-ptr2)) 524287))
560                      -6) 1023))
561     (logand (lsh (random) math-random-shift) 1023))
562 )
563 (setq math-random-table nil)
564 (setq math-last-RandSeed nil)
565 (setq math-random-ptr1 nil)
566 (setq math-random-ptr2 nil)
567 (setq math-random-shift nil)
568
569
570 ;;; Produce a random digit in the range 0..999.
571 ;;; Avoid various pitfalls that may lurk in the built-in (random) function!
572 ;;; Shuffling algorithm from Numerical Recipes, section 7.1.
573 (defun math-random-digit ()
574   (let (i)
575     (or (and (boundp 'var-RandSeed) (eq var-RandSeed math-last-RandSeed))
576         (math-init-random-base))
577     (or math-random-cache
578         (progn
579           (setq math-random-last (math-random-base)
580                 math-random-cache (make-vector 13 nil)
581                 i -1)
582           (while (< (setq i (1+ i)) 13)
583             (aset math-random-cache i (math-random-base)))))
584     (while (progn
585              (setq i (/ math-random-last 79)   ; 0 <= i < 13
586                    math-random-last (aref math-random-cache i))
587              (aset math-random-cache i (math-random-base))
588              (>= math-random-last 1000)))
589     math-random-last)
590 )
591 (setq math-random-cache nil)
592
593 ;;; Produce an N-digit random integer.
594 (defun math-random-digits (n)
595   (cond ((<= n 6)
596          (math-scale-right (+ (* (math-random-digit) 1000) (math-random-digit))
597                            (- 6 n)))
598         (t (let* ((slop (% (- 900003 n) 3))
599                   (i (/ (+ n slop) 3))
600                   (digs nil))
601              (while (> i 0)
602                (setq digs (cons (math-random-digit) digs)
603                      i (1- i)))
604              (math-normalize (math-scale-right (cons 'bigpos digs)
605                                                slop)))))
606 )
607
608 ;;; Produce a uniformly-distributed random float 0 <= N < 1.
609 (defun math-random-float ()
610   (math-make-float (math-random-digits calc-internal-prec)
611                    (- calc-internal-prec))
612 )
613
614 ;;; Produce a Gaussian-distributed random float with mean=0, sigma=1.
615 (defun math-gaussian-float ()
616   (math-with-extra-prec 2
617     (if (and math-gaussian-cache
618              (= (car math-gaussian-cache) calc-internal-prec))
619         (prog1
620             (cdr math-gaussian-cache)
621           (setq math-gaussian-cache nil))
622       (let* ((v1 (math-add (math-mul (math-random-float) 2) -1))
623              (v2 (math-add (math-mul (math-random-float) 2) -1))
624              (r (math-add (math-sqr v1) (math-sqr v2))))
625         (while (or (not (Math-lessp r 1)) (math-zerop r))
626           (setq v1 (math-add (math-mul (math-random-float) 2) -1)
627                 v2 (math-add (math-mul (math-random-float) 2) -1)
628                 r (math-add (math-sqr v1) (math-sqr v2))))
629         (let ((fac (math-sqrt (math-mul (math-div (calcFunc-ln r) r) -2))))
630           (setq math-gaussian-cache (cons calc-internal-prec
631                                           (math-mul v1 fac)))
632           (math-mul v2 fac)))))
633 )
634 (setq math-gaussian-cache nil)
635
636 ;;; Produce a random integer or real 0 <= N < MAX.
637 (defun calcFunc-random (max)
638   (cond ((Math-zerop max)
639          (math-gaussian-float))
640         ((Math-integerp max)
641          (let* ((digs (math-numdigs max))
642                 (r (math-random-digits (+ digs 3))))
643            (math-mod r max)))
644         ((Math-realp max)
645          (math-mul (math-random-float) max))
646         ((and (eq (car max) 'intv) (math-constp max)
647               (Math-lessp (nth 2 max) (nth 3 max)))
648          (if (math-floatp max)
649              (let ((val (math-add (math-mul (math-random-float)
650                                             (math-sub (nth 3 max) (nth 2 max)))
651                                   (nth 2 max))))
652                (if (or (and (memq (nth 1 max) '(0 1))      ; almost not worth
653                             (Math-equal val (nth 2 max)))  ;   checking!
654                        (and (memq (nth 1 max) '(0 2))
655                             (Math-equal val (nth 3 max))))
656                    (calcFunc-random max)
657                  val))
658            (let ((lo (if (memq (nth 1 max) '(0 1))
659                          (math-add (nth 2 max) 1) (nth 2 max)))
660                  (hi (if (memq (nth 1 max) '(1 3))
661                          (math-add (nth 3 max) 1) (nth 3 max))))
662              (if (Math-lessp lo hi)
663                  (math-add (calcFunc-random (math-sub hi lo)) lo)
664                (math-reject-arg max "*Empty interval")))))
665         ((eq (car max) 'vec)
666          (if (cdr max)
667              (nth (1+ (calcFunc-random (1- (length max)))) max)
668            (math-reject-arg max "*Empty list")))
669         ((and (eq (car max) 'sdev) (math-constp max) (Math-realp (nth 1 max)))
670          (math-add (math-mul (math-gaussian-float) (nth 2 max)) (nth 1 max)))
671         (t (math-reject-arg max 'realp)))
672 )
673
674 ;;; Choose N objects at random from the set MAX without duplicates.
675 (defun calcFunc-shuffle (n &optional max)
676   (or max (setq max n n -1))
677   (or (and (Math-num-integerp n)
678            (or (natnump (setq n (math-trunc n))) (eq n -1)))
679       (math-reject-arg n 'integerp))
680   (cond ((or (math-zerop max)
681              (math-floatp max)
682              (eq (car-safe max) 'sdev))
683          (if (< n 0)
684              (math-reject-arg n 'natnump)
685            (math-simple-shuffle n max)))
686         ((and (<= n 1) (>= n 0))
687          (math-simple-shuffle n max))
688         ((and (eq (car-safe max) 'intv) (math-constp max))
689          (let ((num (math-add (math-sub (nth 3 max) (nth 2 max))
690                               (cdr (assq (nth 1 max)
691                                          '((0 . -1) (1 . 0)
692                                            (2 . 0) (3 . 1))))))
693                (min (math-add (nth 2 max) (if (memq (nth 1 max) '(0 1))
694                                               1 0))))
695            (if (< n 0) (setq n num))
696            (or (math-posp num) (math-reject-arg max 'range))
697            (and (Math-lessp num n) (math-reject-arg n 'range))
698            (if (Math-lessp n (math-quotient num 3))
699                (math-simple-shuffle n max)
700              (if (> (* n 4) (* num 3))
701                  (math-add (math-sub min 1)
702                            (math-shuffle-list n num (calcFunc-index num)))
703                (let ((tot 0)
704                      (m 0)
705                      (vec nil))
706                  (while (< m n)
707                    (if (< (calcFunc-random (- num tot)) (- n m))
708                        (setq vec (cons (math-add min tot) vec)
709                              m (1+ m)))
710                    (setq tot (1+ tot)))
711                  (math-shuffle-list n n (cons 'vec vec)))))))
712         ((eq (car-safe max) 'vec)
713          (let ((size (1- (length max))))
714            (if (< n 0) (setq n size))
715            (if (and (> n (/ size 2)) (<= n size))
716                (math-shuffle-list n size (copy-sequence max))
717              (let* ((vals (calcFunc-shuffle
718                            n (list 'intv 3 1 (1- (length max)))))
719                     (p vals))
720                (while (setq p (cdr p))
721                  (setcar p (nth (car p) max)))
722                vals))))
723         ((math-integerp max)
724          (if (math-posp max)
725              (calcFunc-shuffle n (list 'intv 2 0 max))
726            (calcFunc-shuffle n (list 'intv 1 max 0))))
727         (t (math-reject-arg max 'realp)))
728 )
729
730 (defun math-simple-shuffle (n max)
731   (let ((vec nil)
732         val)
733     (while (>= (setq n (1- n)) 0)
734       (while (math-member (setq val (calcFunc-random max)) vec))
735       (setq vec (cons val vec)))
736     (cons 'vec vec))
737 )
738
739 (defun math-shuffle-list (n size vec)
740   (let ((j size)
741         k temp
742         (p vec))
743     (while (cdr (setq p (cdr p)))
744       (setq k (calcFunc-random j)
745             j (1- j)
746             temp (nth k p))
747       (setcar (nthcdr k p) (car p))
748       (setcar p temp))
749     (cons 'vec (nthcdr (- size n -1) vec)))
750 )
751
752 (defun math-member (x list)
753   (while (and list (not (equal x (car list))))
754     (setq list (cdr list)))
755   list
756 )
757
758
759 ;;; Check if the integer N is prime.  [X I]
760 ;;; Return (nil) if non-prime,
761 ;;;        (nil N) if non-prime with known factor N,
762 ;;;        (nil unknown) if non-prime with no known factors,
763 ;;;        (t) if prime,
764 ;;;        (maybe N P) if probably prime (after N iters with probability P%)
765 (defun math-prime-test (n iters)
766   (if (and (Math-vectorp n) (cdr n))
767       (setq n (nth (1- (length n)) n)))
768   (if (Math-messy-integerp n)
769       (setq n (math-trunc n)))
770   (let ((res))
771     (while (> iters 0)
772       (setq res
773             (cond ((and (integerp n) (<= n 5003))
774                    (list (= (math-next-small-prime n) n)))
775                   ((not (Math-integerp n))
776                    (error "Argument must be an integer"))
777                   ((Math-integer-negp n)
778                    '(nil))
779                   ((Math-natnum-lessp n '(bigpos 0 0 8))
780                    (setq n (math-fixnum n))
781                    (let ((i -1) v)
782                      (while (and (> (% n (setq v (aref math-primes-table
783                                                        (setq i (1+ i)))))
784                                     0)
785                                  (< (* v v) n)))
786                      (if (= (% n v) 0)
787                          (list nil v)
788                        '(t))))
789                   ((not (equal n (car math-prime-test-cache)))
790                    (cond ((= (% (nth 1 n) 2) 0) '(nil 2))
791                          ((= (% (nth 1 n) 5) 0) '(nil 5))
792                          (t (let ((dig (cdr n)) (sum 0))
793                               (while dig
794                                 (if (cdr dig)
795                                     (setq sum (% (+ (+ sum (car dig))
796                                                     (* (nth 1 dig) 1000))
797                                                  111111)
798                                           dig (cdr (cdr dig)))
799                                   (setq sum (% (+ sum (car dig)) 111111)
800                                         dig nil)))
801                               (cond ((= (% sum 3) 0) '(nil 3))
802                                     ((= (% sum 7) 0) '(nil 7))
803                                     ((= (% sum 11) 0) '(nil 11))
804                                     ((= (% sum 13) 0) '(nil 13))
805                                     ((= (% sum 37) 0) '(nil 37))
806                                     (t
807                                      (setq math-prime-test-cache-k 1
808                                            math-prime-test-cache-q
809                                            (math-div2 n)
810                                            math-prime-test-cache-nm1
811                                            (math-add n -1))
812                                      (while (math-evenp
813                                              math-prime-test-cache-q)
814                                        (setq math-prime-test-cache-k
815                                              (1+ math-prime-test-cache-k)
816                                              math-prime-test-cache-q
817                                              (math-div2
818                                               math-prime-test-cache-q)))
819                                      (setq iters (1+ iters))
820                                      (list 'maybe
821                                            0
822                                            (math-sub
823                                             100
824                                             (math-div
825                                              '(float 232 0)
826                                              (math-numdigs n))))))))))
827                   ((not (eq (car (nth 1 math-prime-test-cache)) 'maybe))
828                    (nth 1 math-prime-test-cache))
829                   (t   ; Fermat step
830                    (let* ((x (math-add (calcFunc-random (math-add n -2)) 2))
831                           (y (math-pow-mod x math-prime-test-cache-q n))
832                           (j 0))
833                      (while (and (not (eq y 1))
834                                  (not (equal y math-prime-test-cache-nm1))
835                                  (< (setq j (1+ j)) math-prime-test-cache-k))
836                        (setq y (math-mod (math-mul y y) n)))
837                      (if (or (equal y math-prime-test-cache-nm1)
838                              (and (eq y 1) (eq j 0)))
839                          (list 'maybe
840                                (1+ (nth 1 (nth 1 math-prime-test-cache)))
841                                (math-mul (nth 2 (nth 1 math-prime-test-cache))
842                                          '(float 25 -2)))
843                        '(nil unknown))))))
844       (setq math-prime-test-cache (list n res)
845             iters (if (eq (car res) 'maybe)
846                       (1- iters)
847                     0)))
848     res)
849 )
850 (defvar math-prime-test-cache '(-1))
851
852 (defun calcFunc-prime (n &optional iters)
853   (or (math-num-integerp n) (math-reject-arg n 'integerp))
854   (or (not iters) (math-num-integerp iters) (math-reject-arg iters 'integerp))
855   (if (car (math-prime-test (math-trunc n) (math-trunc (or iters 1))))
856       1
857     0)
858 )
859
860 ;;; Theory: summing base-10^6 digits modulo 111111 is "casting out 999999s".
861 ;;; Initial probability that N is prime is 1/ln(N) = log10(e)/log10(N).
862 ;;; After culling [2,3,5,7,11,13,37], probability of primality is 5.36 x more.
863 ;;; Initial reported probability of non-primality is thus 100% - this.
864 ;;; Each Fermat step multiplies this probability by 25%.
865 ;;; The Fermat step is algorithm P from Knuth section 4.5.4.
866
867
868 (defun calcFunc-prfac (n)
869   (setq math-prime-factors-finished t)
870   (if (Math-messy-integerp n)
871       (setq n (math-trunc n)))
872   (if (Math-natnump n)
873       (if (Math-natnum-lessp 2 n)
874           (let (factors res p (i 0))
875             (while (and (not (eq n 1))
876                         (< i (length math-primes-table)))
877               (setq p (aref math-primes-table i))
878               (while (eq (cdr (setq res (cond ((eq n p) (cons 1 0))
879                                               ((eq n 1) (cons 0 1))
880                                               ((consp n) (math-idivmod n p))
881                                               (t (cons (/ n p) (% n p))))))
882                          0)
883                 (math-working "factor" p)
884                 (setq factors (nconc factors (list p))
885                       n (car res)))
886               (or (eq n 1)
887                   (Math-natnum-lessp p (car res))
888                   (setq factors (nconc factors (list n))
889                         n 1))
890               (setq i (1+ i)))
891             (or (setq math-prime-factors-finished (eq n 1))
892                 (setq factors (nconc factors (list n))))
893             (cons 'vec factors))
894         (list 'vec n))
895     (if (Math-integerp n)
896         (if (eq n -1)
897             (list 'vec n)
898           (cons 'vec (cons -1 (cdr (calcFunc-prfac (math-neg n))))))
899       (calc-record-why 'integerp n)
900       (list 'calcFunc-prfac n)))
901 )
902
903 (defun calcFunc-totient (n)
904   (if (Math-messy-integerp n)
905       (setq n (math-trunc n)))
906   (if (Math-natnump n)
907       (if (Math-natnum-lessp n 2)
908           (if (Math-negp n)
909               (calcFunc-totient (math-abs n))
910             n)
911         (let ((factors (cdr (calcFunc-prfac n)))
912               p)
913           (if math-prime-factors-finished
914               (progn
915                 (while factors
916                   (setq p (car factors)
917                         n (math-mul (math-div n p) (math-add p -1)))
918                   (while (equal p (car factors))
919                     (setq factors (cdr factors))))
920                 n)
921             (calc-record-why "*Number too big to factor" n)
922             (list 'calcFunc-totient n))))
923     (calc-record-why 'natnump n)
924     (list 'calcFunc-totient n))
925 )
926
927 (defun calcFunc-moebius (n)
928   (if (Math-messy-integerp n)
929       (setq n (math-trunc n)))
930   (if (and (Math-natnump n) (not (eq n 0)))
931       (if (Math-natnum-lessp n 2)
932           (if (Math-negp n)
933               (calcFunc-moebius (math-abs n))
934             1)
935         (let ((factors (cdr (calcFunc-prfac n)))
936               (mu 1))
937           (if math-prime-factors-finished
938               (progn
939                 (while factors
940                   (setq mu (if (equal (car factors) (nth 1 factors))
941                                0 (math-neg mu))
942                         factors (cdr factors)))
943                 mu)
944             (calc-record-why "Number too big to factor" n)
945             (list 'calcFunc-moebius n))))
946     (calc-record-why 'posintp n)
947     (list 'calcFunc-moebius n))
948 )
949
950
951 (defun calcFunc-nextprime (n &optional iters)
952   (if (Math-integerp n)
953       (if (Math-integer-negp n)
954           2
955         (if (and (integerp n) (< n 5003))
956             (math-next-small-prime (1+ n))
957           (if (math-evenp n)
958               (setq n (math-add n -1)))
959           (let (res)
960             (while (not (car (setq res (math-prime-test
961                                         (setq n (math-add n 2))
962                                         (or iters 1))))))
963             (if (and calc-verbose-nextprime
964                      (eq (car res) 'maybe))
965                 (calc-report-prime-test res)))
966           n))
967     (if (Math-realp n)
968         (calcFunc-nextprime (math-trunc n) iters)
969       (math-reject-arg n 'integerp)))
970 )
971 (setq calc-verbose-nextprime nil)
972
973 (defun calcFunc-prevprime (n &optional iters)
974   (if (Math-integerp n)
975       (if (Math-lessp n 4)
976           2
977         (if (math-evenp n)
978             (setq n (math-add n 1)))
979         (let (res)
980           (while (not (car (setq res (math-prime-test
981                                       (setq n (math-add n -2))
982                                       (or iters 1))))))
983           (if (and calc-verbose-nextprime
984                    (eq (car res) 'maybe))
985               (calc-report-prime-test res)))
986         n)
987     (if (Math-realp n)
988         (calcFunc-prevprime (math-ceiling n) iters)
989       (math-reject-arg n 'integerp)))
990 )
991
992 (defun math-next-small-prime (n)
993   (if (and (integerp n) (> n 2))
994       (let ((lo -1)
995             (hi (length math-primes-table))
996             mid)
997         (while (> (- hi lo) 1)
998           (if (> n (aref math-primes-table
999                          (setq mid (ash (+ lo hi) -1))))
1000               (setq lo mid)
1001             (setq hi mid)))
1002         (aref math-primes-table hi))
1003     2)
1004 )
1005
1006 (defconst math-primes-table
1007   [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
1008      97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
1009      191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277
1010      281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383
1011      389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487
1012      491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601
1013      607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709
1014      719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827
1015      829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947
1016      953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049
1017      1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151
1018      1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249
1019      1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361
1020      1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459
1021      1471 1481 1483 1487 1489 1493 1499 1511 1523 1531 1543 1549 1553 1559
1022      1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657
1023      1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759
1024      1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877
1025      1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987 1993 1997
1026      1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087 2089
1027      2099 2111 2113 2129 2131 2137 2141 2143 2153 2161 2179 2203 2207 2213
1028      2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297 2309 2311
1029      2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411
1030      2417 2423 2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543
1031      2549 2551 2557 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663
1032      2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741
1033      2749 2753 2767 2777 2789 2791 2797 2801 2803 2819 2833 2837 2843 2851
1034      2857 2861 2879 2887 2897 2903 2909 2917 2927 2939 2953 2957 2963 2969
1035      2971 2999 3001 3011 3019 3023 3037 3041 3049 3061 3067 3079 3083 3089
1036      3109 3119 3121 3137 3163 3167 3169 3181 3187 3191 3203 3209 3217 3221
1037      3229 3251 3253 3257 3259 3271 3299 3301 3307 3313 3319 3323 3329 3331
1038      3343 3347 3359 3361 3371 3373 3389 3391 3407 3413 3433 3449 3457 3461
1039      3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539 3541 3547 3557
1040      3559 3571 3581 3583 3593 3607 3613 3617 3623 3631 3637 3643 3659 3671
1041      3673 3677 3691 3697 3701 3709 3719 3727 3733 3739 3761 3767 3769 3779
1042      3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907
1043      3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013
1044      4019 4021 4027 4049 4051 4057 4073 4079 4091 4093 4099 4111 4127 4129
1045      4133 4139 4153 4157 4159 4177 4201 4211 4217 4219 4229 4231 4241 4243
1046      4253 4259 4261 4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363
1047      4373 4391 4397 4409 4421 4423 4441 4447 4451 4457 4463 4481 4483 4493
1048      4507 4513 4517 4519 4523 4547 4549 4561 4567 4583 4591 4597 4603 4621
1049      4637 4639 4643 4649 4651 4657 4663 4673 4679 4691 4703 4721 4723 4729
1050      4733 4751 4759 4783 4787 4789 4793 4799 4801 4813 4817 4831 4861 4871
1051      4877 4889 4903 4909 4919 4931 4933 4937 4943 4951 4957 4967 4969 4973
1052      4987 4993 4999 5003])
1053
1054
1055
1056