Library Stdlib.PArith.BinPosDef
Binary positive numbers, operations
Initial development by Pierre Crégut, CNET, Lannion, France
The type
positive and its constructors
xI and
xO and
xH
are now defined in
BinNums.v
Operations over positive numbers
Infix "+" :=
add :
positive_scope.
Number of digits in a positive number
Same, with positive output
Boolean equality and comparisons
Definition ltb x y :=
match x ?= y with Lt =>
true |
_ =>
false end.
Infix "=?" :=
eqb (
at level 70,
no associativity) :
positive_scope.
Infix "<=?" :=
leb (
at level 70,
no associativity) :
positive_scope.
Infix "<?" :=
ltb (
at level 70,
no associativity) :
positive_scope.
Instead of the Euclid algorithm, we use here the Stein binary
algorithm, which is faster for this representation. This algorithm
is almost structural, but in the last cases we do some recursive
calls on subtraction, hence the need for a counter.
We'll show later that we need at most (log2(a.b)) loops
Generalized Gcd, also computing the division of a and b by the gcd
Set Printing Universes.
Fixpoint ggcdn (
n :
nat) (
a b :
positive) : (
positive*(positive*positive)) :=
match n with
|
O =>
(1
,(a,b))
|
S n =>
match a,
b with
| 1,
_ =>
(1
,(1
,b))
|
_, 1 =>
(1
,(a,1
))
|
a~0,
b~0 =>
let (
g,
p) :=
ggcdn n a b in
(g~0,p)
|
_,
b~0 =>
let '
(g,(aa,bb)) :=
ggcdn n a b in
(g,(aa, bb~0))
|
a~0,
_ =>
let '
(g,(aa,bb)) :=
ggcdn n a b in
(g,(aa~0, bb))
|
a'~1,
b'~1 =>
match a' ?= b' with
|
Eq =>
(a,(1
,1
))
|
Lt =>
let '
(g,(ba,aa)) :=
ggcdn n (
b'-a')
a in
(g,(aa, aa + ba~0))
|
Gt =>
let '
(g,(ab,bb)) :=
ggcdn n (
a'-b')
b in
(g,(bb + ab~0, bb))
end
end
end.
Definition ggcd (
a b:
positive) :=
ggcdn (
size_nat a + size_nat b)%
nat a b.
Shifts. NB: right shift of 1 stays at 1.
Checking whether a particular bit is set or not
Same, but with index in N
From Peano natural numbers to binary positive numbers
A version preserving positive numbers, and sending 0 to 1.
Conversion with a decimal representation for printing/parsing
Re-export the notation for those who just Import BinPosDef