Library Stdlib.NArith.BinNatDef
From Stdlib Require Export BinNums.
From Stdlib Require Import BinPos.
From Stdlib Require Export BinNums.NatDef.
Local Open Scope N_scope.
Local Notation "0" :=
N0.
Local Notation "1" := (
Npos 1).
Local Notation "2" := (
Npos 2).
Binary natural numbers, definitions of operations
Nicer name N.pos for constructor Npos
Definition zero := 0.
Definition one := 1.
Definition two := 2.
Definition add n m :=
match n,
m with
| 0,
_ =>
m
|
_, 0 =>
n
|
pos p,
pos q =>
pos (
p + q)
end.
Infix "+" :=
add :
N_scope.
Infix "-" :=
sub :
N_scope.
Multiplication
Definition mul n m :=
match n,
m with
| 0,
_ => 0
|
_, 0 => 0
|
pos p,
pos q =>
pos (
p * q)
end.
Infix "*" :=
mul :
N_scope.
Infix "?=" :=
compare (
at level 70,
no associativity) :
N_scope.
Boolean equality and comparison
Definition eqb n m :=
match n,
m with
| 0, 0 =>
true
|
pos p,
pos q =>
Pos.eqb p q
|
_,
_ =>
false
end.
Definition ltb x y :=
match x ?= y with Lt =>
true |
_ =>
false end.
Infix "=?" :=
eqb (
at level 70,
no associativity) :
N_scope.
Infix "<=?" :=
leb (
at level 70,
no associativity) :
N_scope.
Infix "<?" :=
ltb (
at level 70,
no associativity) :
N_scope.
Min and max
Dividing by 2
Parity
Power
Definition pow n p :=
match p,
n with
| 0,
_ => 1
|
_, 0 => 0
|
pos p,
pos q =>
pos (
q^p)
end.
Infix "^" :=
pow :
N_scope.
Square
Base-2 logarithm
How many digits in a number ?
Number 0 is said to have no digits at all.
Euclidean division
Greatest common divisor
Generalized Gcd, also computing rests of a and b after
division by gcd.
Definition ggcd a b :=
match a,
b with
| 0,
_ =>
(b,(0
,1
))
|
_, 0 =>
(a,(1
,0
))
|
pos p,
pos q =>
let '
(g,(aa,bb)) :=
Pos.ggcd p q in
(pos g, (pos aa, pos bb))
end.
Square root
Shifts
Checking whether a particular bit is set or not
Same, but with index in N
Translation from N to nat and back.
Iteration of a function
Iteration of an associative operator
Conversion with a decimal representation for printing/parsing
Re-export the notation for those who just Import NatIntDef