Debian Codegraph @

src/c/num_arith.d

raw
1 /* -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /* vim: set filetype=c tabstop=2 shiftwidth=2 expandtab: */
3
4 /*
5 * num_arith.d - arithmetic operations
6 *
7 * Copyright (c) 1990 Giuseppe Attardi
8 * Copyright (c) 2001 Juan Jose Garcia Ripoll
9 *
10 * See file 'LICENSE' for the copyright details.
11 *
12 */
13
14 #include <ecl/ecl.h>
15 #include <ecl/number.h>
16 #include <stdlib.h>
17 #include <ecl/impl/math_dispatch2.h>
18
19 cl_object
20 ecl_integer_divide(cl_object x, cl_object y)
21 {
22 MATH_DISPATCH2_BEGIN(x,y) {
23 CASE_FIXNUM_FIXNUM;
24 if (y == ecl_make_fixnum(0)) {
25 FEdivision_by_zero(x,y);
26 }
27 return ecl_make_fixnum(ecl_fixnum(x) / ecl_fixnum(y));
28 CASE_FIXNUM_BIGNUM return _ecl_fix_divided_by_big(ecl_fixnum(x), y);
29 CASE_BIGNUM_FIXNUM return _ecl_big_divided_by_fix(x, ecl_fixnum(y));
30 CASE_BIGNUM_BIGNUM return _ecl_big_divided_by_big(x, y);
31 CASE_UNKNOWN(@[round],x,y,@[integer]);
32 }
33 MATH_DISPATCH2_END;
34 }
35
36 @(defun gcd (&rest nums)
37 cl_object gcd;
38 @
39 if (narg == 0) {
40 @(return ecl_make_fixnum(0));
41 }
42 /* INV: ecl_gcd() checks types */
43 gcd = ecl_va_arg(nums);
44 if (narg == 1) {
45 assert_type_integer(gcd);
46 @(return (ecl_minusp(gcd) ? ecl_negate(gcd) : gcd));
47 }
48 while (--narg)
49 gcd = ecl_gcd(gcd, ecl_va_arg(nums));
50 @(return gcd);
51 @)
52
53 cl_object
54 ecl_gcd(cl_object x, cl_object y)
55 {
56 ECL_WITH_TEMP_BIGNUM(x_big,1);
57 ECL_WITH_TEMP_BIGNUM(y_big,1);
58
59 switch (ecl_t_of(x)) {
60 case t_fixnum:
61 _ecl_big_set_fixnum(x_big, ecl_fixnum(x));
62 x = x_big;
63 case t_bignum:
64 break;
65 default:
66 FEwrong_type_nth_arg(@[gcd], 1, x, @[integer]);
67 }
68 switch (ecl_t_of(y)) {
69 case t_fixnum:
70 _ecl_big_set_fixnum(y_big, ecl_fixnum(y));
71 y = y_big;
72 case t_bignum:
73 break;
74 default:
75 FEwrong_type_nth_arg(@[gcd], 2, y, @[integer]);
76 }
77 return _ecl_big_gcd(x, y);
78 }
79
80 @(defun lcm (&rest nums)
81 cl_object lcm;
82 @
83 if (narg == 0) {
84 @(return ecl_make_fixnum(1));
85 }
86 /* INV: ecl_gcd() checks types. By placing `numi' before `lcm' in
87 this call, we make sure that errors point to `numi' */
88 lcm = ecl_va_arg(nums);
89 assert_type_integer(lcm);
90 while (narg-- > 1) {
91 cl_object numi = ecl_va_arg(nums);
92 cl_object t = ecl_times(lcm, numi);
93 cl_object g = ecl_gcd(numi, lcm);
94 if (g != ecl_make_fixnum(0))
95 lcm = ecl_divide(t, g);
96 }
97 @(return (ecl_minusp(lcm) ? ecl_negate(lcm) : lcm));
98 @)