factor/library/math/integer.factor

111 lines
2.4 KiB
Factor
Raw Normal View History

! Copyright (C) 2004, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: math
USING: errors generic kernel math sequences ;
UNION: integer fixnum bignum ;
2004-12-24 02:52:02 -05:00
: (gcd) ( b a y x -- a d )
dup 0 number= [
drop nip
] [
tuck /mod >r pick * swap >r swapd - r> r> (gcd)
] ifte ; inline
: gcd ( x y -- a d )
#! Compute the greatest common divisor d and multiplier a
#! such that a*x=d mod y.
swap 0 1 2swap (gcd) abs ; foldable
: lcm ( a b -- c )
#! Smallest integer such that c/a and c/b are both integers.
2dup gcd nip >r * r> /i ;
: mod-inv ( x n -- y )
#! Compute the multiplicative inverse of x mod n.
gcd 1 = [ "Non-trivial divisor found" throw ] unless ; foldable
: bitroll ( n s w -- n )
#! Roll n by s bits to the right, wrapping around after
#! w bits.
[ mod shift ] 3keep over 0 >= [ - ] [ + ] ifte shift bitor ;
foldable
IN: math-internals
2004-07-16 02:26:21 -04:00
2004-12-24 02:52:02 -05:00
: fraction> ( a b -- a/b )
2004-12-30 02:40:14 -05:00
dup 1 number= [
drop
2004-12-24 02:52:02 -05:00
] [
2004-12-30 02:40:14 -05:00
(fraction>)
] ifte ; inline
2004-12-24 02:52:02 -05:00
2004-12-30 20:46:20 -05:00
: division-by-zero ( x y -- )
"Division by zero" throw drop ; inline
2004-12-30 20:46:20 -05:00
M: integer / ( x y -- x/y )
2004-12-30 02:40:14 -05:00
dup 0 number= [
2004-12-30 20:46:20 -05:00
division-by-zero
2004-12-30 02:40:14 -05:00
] [
dup 0 < [
swap neg swap neg
] when
2dup gcd nip tuck /i >r /i r> fraction>
] ifte ;
2004-07-16 02:26:21 -04:00
M: fixnum number=
#! Fixnums are immediate values, so equality testing is
#! trivial.
eq? ;
M: fixnum < fixnum< ;
M: fixnum <= fixnum<= ;
M: fixnum > fixnum> ;
M: fixnum >= fixnum>= ;
2004-07-16 02:26:21 -04:00
M: fixnum + fixnum+ ;
M: fixnum - fixnum- ;
M: fixnum * fixnum* ;
M: fixnum /i fixnum/i ;
M: fixnum /f fixnum/f ;
M: fixnum mod fixnum-mod ;
2004-07-16 02:26:21 -04:00
M: fixnum /mod fixnum/mod ;
2004-07-16 02:26:21 -04:00
M: fixnum bitand fixnum-bitand ;
M: fixnum bitor fixnum-bitor ;
M: fixnum bitxor fixnum-bitxor ;
M: fixnum shift fixnum-shift ;
2004-07-16 02:26:21 -04:00
M: fixnum bitnot fixnum-bitnot ;
2004-11-08 22:36:51 -05:00
M: bignum number= bignum= ;
M: bignum < bignum< ;
M: bignum <= bignum<= ;
M: bignum > bignum> ;
M: bignum >= bignum>= ;
2004-11-08 22:36:51 -05:00
M: bignum + bignum+ ;
M: bignum - bignum- ;
M: bignum * bignum* ;
M: bignum /i bignum/i ;
M: bignum /f bignum/f ;
M: bignum mod bignum-mod ;
M: bignum /mod bignum/mod ;
M: bignum bitand bignum-bitand ;
M: bignum bitor bignum-bitor ;
M: bignum bitxor bignum-bitxor ;
M: bignum shift bignum-shift ;
M: bignum bitnot bignum-bitnot ;
M: integer truncate ;
M: integer floor ;
M: integer ceiling ;
! Integers support the sequence protocol
M: integer length ;
M: integer nth drop ;