• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #38002

06 Feb 2025 06:14AM UTC coverage: 20.322% (-2.4%) from 22.722%
#38002

push

local

web-flow
bpart: Fully switch to partitioned semantics (#57253)

This is the final PR in the binding partitions series (modulo bugs and
tweaks), i.e. it closes #54654 and thus closes #40399, which was the
original design sketch.

This thus activates the full designed semantics for binding partitions,
in particular allowing safe replacement of const bindings. It in
particular allows struct redefinitions. This thus closes
timholy/Revise.jl#18 and also closes #38584.

The biggest semantic change here is probably that this gets rid of the
notion of "resolvedness" of a binding. Previously, a lot of the behavior
of our implementation depended on when bindings were "resolved", which
could happen at basically an arbitrary point (in the compiler, in REPL
completion, in a different thread), making a lot of the semantics around
bindings ill- or at least implementation-defined. There are several
related issues in the bugtracker, so this closes #14055 closes #44604
closes #46354 closes #30277

It is also the last step to close #24569.
It also supports bindings for undef->defined transitions and thus closes
#53958 closes #54733 - however, this is not activated yet for
performance reasons and may need some further optimization.

Since resolvedness no longer exists, we need to replace it with some
hopefully more well-defined semantics. I will describe the semantics
below, but before I do I will make two notes:

1. There are a number of cases where these semantics will behave
slightly differently than the old semantics absent some other task going
around resolving random bindings.
2. The new behavior (except for the replacement stuff) was generally
permissible under the old semantics if the bindings happened to be
resolved at the right time.

With all that said, there are essentially three "strengths" of bindings:

1. Implicit Bindings: Anything implicitly obtained from `using Mod`, "no
binding", plus slightly more exotic corner cases around conflicts

2. Weakly declared bindin... (continued)

11 of 111 new or added lines in 7 files covered. (9.91%)

1273 existing lines in 68 files now uncovered.

9908 of 48755 relevant lines covered (20.32%)

105126.48 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.99
/base/intfuncs.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
## number-theoretic functions ##
4

5
"""
6
    gcd(x, y...)
7

8
Greatest common (positive) divisor (or zero if all arguments are zero).
9
The arguments may be integer and rational numbers.
10

11
!!! compat "Julia 1.4"
12
    Rational arguments require Julia 1.4 or later.
13

14
# Examples
15
```jldoctest
16
julia> gcd(6, 9)
17
3
18

19
julia> gcd(6, -9)
20
3
21

22
julia> gcd(6, 0)
23
6
24

25
julia> gcd(0, 0)
26
0
27

28
julia> gcd(1//3, 2//3)
29
1//3
30

31
julia> gcd(1//3, -2//3)
32
1//3
33

34
julia> gcd(1//3, 2)
35
1//3
36

37
julia> gcd(0, 0, 10, 15)
38
5
39
```
40
"""
41
function gcd(a::T, b::T) where T<:Integer
×
42
    while b != 0
×
43
        t = b
×
44
        b = rem(a, b)
×
45
        a = t
×
46
    end
×
47
    checked_abs(a)
×
48
end
49

50
function gcd(a::T, b::T) where T<:BitInteger
×
51
    a == 0 && return Base.checked_abs(b)
×
52
    b == 0 && return Base.checked_abs(a)
×
53
    if a isa Signed && a == typemin(T)
×
54
        if a == b
×
55
            Base.__throw_gcd_overflow(a, b)
×
56
        else
57
            a, b = b, a
×
58
        end
59
    end
60
    return _gcd(a, b)
×
61
end
62
@noinline __throw_gcd_overflow(a, b) =
×
63
    throw(OverflowError(LazyString("gcd(", a, ", ", b, ") overflows")))
64

65
function absdiff(x::T,y::T) where {T<:Unsigned}
×
66
    d = max(x,y) - min(x,y)
×
67
    d, d
×
68
end
69
function absdiff(x::T,y::T) where {T<:Signed}
×
70
    d = x - y
×
71
    abs(d), d
×
72
end
73
# binary GCD (aka Stein's) algorithm
74
# about 1.7x (2.1x) faster for random Int64s (Int128s)
75
# Unfortunately, we need to manually annotate this as `@assume_effects :terminates_locally` to work around #41694.
76
# Since this is used in the Rational constructor, constant folding is something we do care about here.
77
@assume_effects :terminates_locally function _gcd(ain::T, bin::T) where T<:BitInteger
×
78
    zb = trailing_zeros(bin)
×
79
    za = trailing_zeros(ain)
×
80
    a = abs(ain)
×
81
    b = abs(bin >> zb)
×
82
    k = min(za, zb)
×
83
    while a != 0
×
84
        a >>= za
×
85
        absd, diff = absdiff(a, b)
×
86
        za = trailing_zeros(diff)
×
87
        b = min(a, b)
×
88
        a = absd
×
89
    end
×
90
    r = b << k
×
91
    return r % T
×
92
end
93

94
"""
95
    lcm(x, y...)
96

97
Least common (positive) multiple (or zero if any argument is zero).
98
The arguments may be integer and rational numbers.
99

100
``a`` is a multiple of ``b`` if there exists an integer ``m`` such
101
that ``a=mb``.
102

103
!!! compat "Julia 1.4"
104
    Rational arguments require Julia 1.4 or later.
105

106
# Examples
107
```jldoctest
108
julia> lcm(2, 3)
109
6
110

111
julia> lcm(-2, 3)
112
6
113

114
julia> lcm(0, 3)
115
0
116

117
julia> lcm(0, 0)
118
0
119

120
julia> lcm(1//3, 2//3)
121
2//3
122

123
julia> lcm(1//3, -2//3)
124
2//3
125

126
julia> lcm(1//3, 2)
127
2//1
128

129
julia> lcm(1, 3, 5, 7)
130
105
131
```
132
"""
133
function lcm(a::T, b::T) where T<:Integer
×
134
    # explicit a==0 test is to handle case of lcm(0, 0) correctly
135
    # explicit b==0 test is to handle case of lcm(typemin(T),0) correctly
136
    if a == 0 || b == 0
×
137
        return zero(a)
×
138
    else
139
        return checked_abs(checked_mul(a, div(b, gcd(b,a))))
×
140
    end
141
end
142

143
gcd(a::Integer) = checked_abs(a)
×
144
gcd(a::Rational) = checked_abs(a.num) // a.den
×
145
lcm(a::Union{Integer,Rational}) = gcd(a)
×
146
gcd(a::Unsigned, b::Signed) = gcd(promote(a, abs(b))...)
×
147
gcd(a::Signed, b::Unsigned) = gcd(promote(abs(a), b)...)
×
148
gcd(a::Real, b::Real) = gcd(promote(a,b)...)
×
149
lcm(a::Real, b::Real) = lcm(promote(a,b)...)
×
150
gcd(a::Real, b::Real, c::Real...) = gcd(a, gcd(b, c...))
×
151
lcm(a::Real, b::Real, c::Real...) = lcm(a, lcm(b, c...))
×
152
gcd(a::T, b::T) where T<:Real = throw(MethodError(gcd, (a,b)))
×
153
lcm(a::T, b::T) where T<:Real = throw(MethodError(lcm, (a,b)))
×
154

155
gcd(abc::AbstractArray{<:Real}) = reduce(gcd, abc; init=zero(eltype(abc)))
×
156
function lcm(abc::AbstractArray{<:Real})
×
157
    # Using reduce with init=one(eltype(abc)) is buggy for Rationals.
158
    l = length(abc)
×
159
    if l == 0
×
160
        eltype(abc) <: Integer && return one(eltype(abc))
×
161
        throw(ArgumentError("lcm has no identity for $(eltype(abc))"))
×
162
    end
163
    l == 1 && return abs(only(abc))
×
164
    return reduce(lcm, abc)
×
165
end
166

167
function gcd(abc::AbstractArray{<:Integer})
×
168
    a = zero(eltype(abc))
×
169
    for b in abc
×
170
        a = gcd(a, b)
×
171
        if a == 1
×
172
            return a
×
173
        end
174
    end
×
175
    return a
×
176
end
177

178
# return (gcd(a, b), x, y) such that ax+by == gcd(a, b)
179
"""
180
    gcdx(a, b...)
181

182
Computes the greatest common (positive) divisor of `a` and `b` and their Bézout
183
coefficients, i.e. the integer coefficients `u` and `v` that satisfy
184
``u*a + v*b = d = gcd(a, b)``. ``gcdx(a, b)`` returns ``(d, u, v)``.
185

186
For more arguments than two, i.e., `gcdx(a, b, c, ...)` the Bézout coefficients are computed
187
recursively, returning a solution `(d, u, v, w, ...)` to
188
``u*a + v*b + w*c + ... = d = gcd(a, b, c, ...)``.
189

190
The arguments may be integer and rational numbers.
191

192
!!! compat "Julia 1.4"
193
    Rational arguments require Julia 1.4 or later.
194

195
!!! compat "Julia 1.12"
196
    More or fewer arguments than two require Julia 1.12 or later.
197

198
# Examples
199
```jldoctest
200
julia> gcdx(12, 42)
201
(6, -3, 1)
202

203
julia> gcdx(240, 46)
204
(2, -9, 47)
205

206
julia> gcdx(15, 12, 20)
207
(1, 7, -7, -1)
208
```
209

210
!!! note
211
    Bézout coefficients are *not* uniquely defined. `gcdx` returns the minimal
212
    Bézout coefficients that are computed by the extended Euclidean algorithm.
213
    (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.)
214
    For signed integers, these coefficients `u` and `v` are minimal in
215
    the sense that ``|u| < |b/d|`` and ``|v| < |a/d|``. Furthermore,
216
    the signs of `u` and `v` are chosen so that `d` is positive.
217
    For unsigned integers, the coefficients `u` and `v` might be near
218
    their `typemax`, and the identity then holds only via the unsigned
219
    integers' modulo arithmetic.
220
"""
221
Base.@assume_effects :terminates_locally function gcdx(a::Integer, b::Integer)
×
222
    T = promote_type(typeof(a), typeof(b))
×
223
    a == b == 0 && return (zero(T), zero(T), zero(T))
×
224
    # a0, b0 = a, b
225
    s0, s1 = oneunit(T), zero(T)
×
226
    t0, t1 = s1, s0
×
227
    # The loop invariant is: s0*a0 + t0*b0 == a && s1*a0 + t1*b0 == b
228
    x = a % T
×
229
    y = b % T
×
230
    while y != 0
×
231
        q, r = divrem(x, y)
×
232
        x, y = y, r
×
233
        s0, s1 = s1, s0 - q*s1
×
234
        t0, t1 = t1, t0 - q*t1
×
235
    end
×
236
    x < 0 ? (-x, -s0, -t0) : (x, s0, t0)
×
237
end
238
gcdx(a::Real, b::Real) = gcdx(promote(a,b)...)
×
239
gcdx(a::T, b::T) where T<:Real = throw(MethodError(gcdx, (a,b)))
×
240
gcdx(a::Real) = (gcd(a), signbit(a) ? -one(a) : one(a))
×
241
function gcdx(a::Real, b::Real, cs::Real...)
×
242
    # a solution to the 3-arg `gcdx(a,b,c)` problem, `u*a + v*b + w*c = gcd(a,b,c)`, can be
243
    # obtained from the 2-arg problem in three steps:
244
    #   1. `gcdx(a,b)`: solve `i*a + j*b = d′ = gcd(a,b)` for `(i,j)`
245
    #   2. `gcdx(d′,c)`: solve `x*gcd(a,b) + yc = gcd(gcd(a,b),c) = gcd(a,b,c)` for `(x,y)`
246
    #   3. return `d = gcd(a,b,c)`, `u = i*x`, `v = j*x`, and `w = y`
247
    # the N-arg solution proceeds similarly by recursion
248
    d, i, j = gcdx(a, b)
×
249
    d′, x, ys... = gcdx(d, cs...)
×
250
    return d′, i*x, j*x, ys...
×
251
end
252

253
# multiplicative inverse of n mod m, error if none
254

255
"""
256
    invmod(n::Integer, m::Integer)
257

258
Take the inverse of `n` modulo `m`: `y` such that ``n y = 1 \\pmod m``,
259
and ``div(y,m) = 0``. This will throw an error if ``m = 0``, or if
260
``gcd(n,m) \\neq 1``.
261

262
# Examples
263
```jldoctest
264
julia> invmod(2, 5)
265
3
266

267
julia> invmod(2, 3)
268
2
269

270
julia> invmod(5, 6)
271
5
272
```
273
"""
274
function invmod(n::Integer, m::Integer)
×
275
    iszero(m) && throw(DomainError(m, "`m` must not be 0."))
×
276
    if n isa Signed && hastypemax(typeof(n))
×
277
        # work around inconsistencies in gcdx
278
        # https://github.com/JuliaLang/julia/issues/33781
279
        T = promote_type(typeof(n), typeof(m))
×
280
        n == typemin(typeof(n)) && m == typeof(n)(-1) && return T(0)
×
281
        n == typeof(n)(-1) && m == typemin(typeof(n)) && return T(-1)
×
282
    end
283
    g, x, y = gcdx(n, m)
×
284
    g != 1 && throw(DomainError((n, m), LazyString("Greatest common divisor is ", g, ".")))
×
285
    # Note that m might be negative here.
286
    if n isa Unsigned && hastypemax(typeof(n)) && x > typemax(n)>>1
×
287
        # x might have wrapped if it would have been negative
288
        # adding back m forces a correction
289
        x += m
×
290
    end
291
    # The postcondition is: mod(result * n, m) == mod(T(1), m) && div(result, m) == 0
292
    return mod(x, m)
×
293
end
294

295
"""
296
    invmod(n::Integer, T) where {T <: Base.BitInteger}
297
    invmod(n::T) where {T <: Base.BitInteger}
298

299
Compute the modular inverse of `n` in the integer ring of type `T`, i.e. modulo
300
`2^N` where `N = 8*sizeof(T)` (e.g. `N = 32` for `Int32`). In other words, these
301
methods satisfy the following identities:
302
```
303
n * invmod(n) == 1
304
(n * invmod(n, T)) % T == 1
305
(n % T) * invmod(n, T) == 1
306
```
307
Note that `*` here is modular multiplication in the integer ring, `T`.  This will
308
throw an error if `n` is even, because then it is not relatively prime with `2^N`
309
and thus has no such inverse.
310

311
Specifying the modulus implied by an integer type as an explicit value is often
312
inconvenient since the modulus is by definition too big to be represented by the
313
type.
314

315
The modular inverse is computed much more efficiently than the general case
316
using the algorithm described in https://arxiv.org/pdf/2204.04342.pdf.
317

318
!!! compat "Julia 1.11"
319
    The `invmod(n)` and `invmod(n, T)` methods require Julia 1.11 or later.
320
"""
321
invmod(n::Integer, ::Type{T}) where {T<:BitInteger} = invmod(n % T)
×
322

323
function invmod(n::T) where {T<:BitInteger}
×
324
    isodd(n) || throw(DomainError(n, "Argument must be odd."))
×
325
    x = (3*n ⊻ 2) % T
×
326
    y = (1 - n*x) % T
×
327
    for _ = 1:trailing_zeros(2*sizeof(T))
×
328
        x *= y + true
×
329
        y *= y
×
330
    end
×
331
    return x
×
332
end
333

334
# ^ for any x supporting *
335
function to_power_type(x::Number)
336
    T = promote_type(typeof(x), typeof(one(x)), typeof(x*x))
×
337
    convert(T, x)
×
338
end
339
to_power_type(x) = oftype(x*x, x)
×
340
@noinline throw_domerr_powbysq(::Any, p) = throw(DomainError(p, LazyString(
×
341
    "Cannot raise an integer x to a negative power ", p, ".",
342
    "\nConvert input to float.")))
343
@noinline throw_domerr_powbysq(::Integer, p) = throw(DomainError(p, LazyString(
×
344
    "Cannot raise an integer x to a negative power ", p, ".",
345
    "\nMake x or ", p, " a float by adding a zero decimal ",
346
    "(e.g., 2.0^", p, " or 2^", float(p), " instead of 2^", p, ") ",
347
    "or write 1/x^", -p, ", float(x)^", p, ", x^float(", p, ") or (x//1)^", p, ".")))
348
@noinline throw_domerr_powbysq(::AbstractMatrix, p) = throw(DomainError(p, LazyString(
×
349
    "Cannot raise an integer matrix x to a negative power ", p, ".",
350
    "\nMake x a float matrix by adding a zero decimal ",
351
    "(e.g., [2.0 1.0;1.0 0.0]^", p, " instead of [2 1;1 0]^", p, ") ",
352
    "or write float(x)^", p, " or Rational.(x)^", p, ".")))
353
# The * keyword supports `*=checked_mul` for `checked_pow`
354
@assume_effects :terminates_locally function power_by_squaring(x_, p::Integer; mul=*)
26✔
355
    x = to_power_type(x_)
×
356
    if p == 1
1✔
357
        return copy(x)
×
358
    elseif p == 0
1✔
359
        return one(x)
1✔
UNCOV
360
    elseif p == 2
×
361
        return mul(x, x)
×
UNCOV
362
    elseif p < 0
×
363
        isone(x) && return copy(x)
×
364
        isone(-x) && return iseven(p) ? one(x) : copy(x)
×
365
        throw_domerr_powbysq(x, p)
×
366
    end
UNCOV
367
    t = trailing_zeros(p) + 1
×
UNCOV
368
    p >>= t
×
UNCOV
369
    while (t -= 1) > 0
×
UNCOV
370
        x = mul(x, x)
×
UNCOV
371
    end
×
372
    y = x
×
UNCOV
373
    while p > 0
×
UNCOV
374
        t = trailing_zeros(p) + 1
×
UNCOV
375
        p >>= t
×
UNCOV
376
        while (t -= 1) >= 0
×
UNCOV
377
            x = mul(x, x)
×
UNCOV
378
        end
×
UNCOV
379
        y = mul(y, x)
×
UNCOV
380
    end
×
UNCOV
381
    return y
×
382
end
383
power_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x)
×
384
function power_by_squaring(x::Bool, p::Integer)
×
385
    p < 0 && !x && throw_domerr_powbysq(x, p)
×
386
    return (p==0) | x
×
387
end
388

389
^(x::T, p::T) where {T<:Integer} = power_by_squaring(x,p)
25✔
390
^(x::Number, p::Integer)  = power_by_squaring(x,p)
×
391

392
# x^p for any literal integer p is lowered to Base.literal_pow(^, x, Val(p))
393
# to enable compile-time optimizations specialized to p.
394
# However, we still need a fallback that calls the function ^ which may either
395
# mean Base.^ or something else, depending on context.
396
# We mark these @inline since if the target is marked @inline,
397
# we want to make sure that gets propagated,
398
# even if it is over the inlining threshold.
399
@inline literal_pow(f, x, ::Val{p}) where {p} = f(x,p)
×
400

401
# Restrict inlining to hardware-supported arithmetic types, which
402
# are fast enough to benefit from inlining.
403
const HWReal = Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64}
404
const HWNumber = Union{HWReal, Complex{<:HWReal}, Rational{<:HWReal}}
405

406
# Inline x^2 and x^3 for Val
407
# (The first argument prevents unexpected behavior if a function ^
408
# is defined that is not equal to Base.^)
409
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{0}) = one(x)
×
410
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{1}) = x
×
411
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{2}) = x*x
3✔
412
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{3}) = x*x*x
2✔
413
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{-1}) = inv(x)
×
414
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{-2}) = (i=inv(x); i*i)
×
415

416
# don't use the inv(x) transformation here since float^p is slightly more accurate
417
@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{p}) where {p} = x^p
×
418
@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{-1}) = inv(x)
×
419

420
# for other types, define x^-n as inv(x)^n so that negative literal powers can
421
# be computed in a type-stable way even for e.g. integers.
422
@inline function literal_pow(f::typeof(^), x, ::Val{p}) where {p}
1✔
423
    if p < 0
×
424
        if x isa BitInteger64
×
425
            f(Float64(x), p) # inv would cause rounding, while Float64^Integer is able to compensate the inverse
×
426
        else
427
            f(inv(x), -p)
×
428
        end
429
    else
430
        f(x, p)
1✔
431
    end
432
end
433

434
# note: it is tempting to add optimized literal_pow(::typeof(^), x, ::Val{n})
435
#       methods here for various n, but this easily leads to method ambiguities
436
#       if anyone has defined literal_pow(::typeof(^), x::T, ::Val).
437

438
# b^p mod m
439

440
"""
441
    powermod(x::Integer, p::Integer, m)
442

443
Compute ``x^p \\pmod m``.
444

445
# Examples
446
```jldoctest
447
julia> powermod(2, 6, 5)
448
4
449

450
julia> mod(2^6, 5)
451
4
452

453
julia> powermod(5, 2, 20)
454
5
455

456
julia> powermod(5, 2, 19)
457
6
458

459
julia> powermod(5, 3, 19)
460
11
461
```
462
"""
463
function powermod(x::Integer, p::Integer, m::T) where T<:Integer
×
464
    p == 0 && return mod(one(m),m)
×
465
    # When the concrete type of p is signed and has the lowest value,
466
    # `p != 0 && p == -p` is equivalent to `p == typemin(typeof(p))` for 2's complement representation.
467
    # but will work for integer types like `BigInt` that don't have `typemin` defined
468
    # It needs special handling otherwise will cause overflow problem.
469
    if p == -p
×
470
        imod = invmod(x, m)
×
471
        rhalf = powermod(imod, -(p÷2), m)
×
472
        r::T = mod(widemul(rhalf, rhalf), m)
×
473
        isodd(p) && (r = mod(widemul(r, imod), m))
×
474
        #else odd
475
        return r
×
476
    elseif p < 0
×
477
        return powermod(invmod(x, m), -p, m)
×
478
    end
479
    (m == 1 || m == -1) && return zero(m)
×
480
    b = oftype(m,mod(x,m))  # this also checks for divide by zero
×
481

482
    t = prevpow(2, p)
×
483
    r = 1
×
484
    while true
×
485
        if p >= t
×
486
            r = mod(widemul(r,b),m)
×
487
            p -= t
×
488
        end
489
        t >>>= 1
×
490
        t <= 0 && break
×
491
        r = mod(widemul(r,r),m)
×
492
    end
×
493
    return r
×
494
end
495

496
# optimization: promote the modulus m to BigInt only once (cf. widemul in generic powermod above)
497
powermod(x::Integer, p::Integer, m::Union{Int128,UInt128}) = oftype(m, powermod(x, p, big(m)))
×
498

499
_nextpow2(x::Unsigned) = oneunit(x)<<(top_set_bit(x-oneunit(x)))
×
500
_nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_nextpow2(unsigned(-x)) : _nextpow2(unsigned(x)))
×
501
_prevpow2(x::Unsigned) = one(x) << unsigned(top_set_bit(x)-1)
×
502
_prevpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_prevpow2(unsigned(-x)) : _prevpow2(unsigned(x)))
×
503

504
"""
505
    ispow2(n::Number) -> Bool
506

507
Test whether `n` is an integer power of two.
508

509
See also [`count_ones`](@ref), [`prevpow`](@ref), [`nextpow`](@ref).
510

511
# Examples
512
```jldoctest
513
julia> ispow2(4)
514
true
515

516
julia> ispow2(5)
517
false
518

519
julia> ispow2(4.5)
520
false
521

522
julia> ispow2(0.25)
523
true
524

525
julia> ispow2(1//8)
526
true
527
```
528

529
!!! compat "Julia 1.6"
530
    Support for non-`Integer` arguments was added in Julia 1.6.
531
"""
532
ispow2(x::Number) = isreal(x) && ispow2(real(x))
×
533

534
ispow2(x::Integer) = x > 0 && count_ones(x) == 1
×
535

536
"""
537
    nextpow(a, x)
538

539
The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be
540
greater than 1, and `x` must be greater than 0.
541

542
See also [`prevpow`](@ref).
543

544
# Examples
545
```jldoctest
546
julia> nextpow(2, 7)
547
8
548

549
julia> nextpow(2, 9)
550
16
551

552
julia> nextpow(5, 20)
553
25
554

555
julia> nextpow(4, 16)
556
16
557
```
558
"""
559
function nextpow(a::Real, x::Real)
×
560
    x <= 0 && throw(DomainError(x, "`x` must be positive."))
×
561
    # Special case fast path for x::Integer, a == 2.
562
    # This is a very common case. Constant prop will make sure that a call site
563
    # specified as `nextpow(2, x)` will get this special case inlined.
564
    a == 2 && isa(x, Integer) && return _nextpow2(x)
×
565
    a <= 1 && throw(DomainError(a, "`a` must be greater than 1."))
×
566
    x <= 1 && return one(a)
×
567
    n = ceil(Integer,log(a, x))
×
568
    # round-off error of log can go either direction, so need some checks
569
    p = a^(n-1)
×
570
    x > typemax(p) && throw(DomainError(x,"argument is beyond the range of type of the base"))
×
571
    p >= x && return p
×
572
    wp = a^n
×
573
    wp > p || throw(OverflowError("result is beyond the range of type of the base"))
×
574
    wp >= x && return wp
×
575
    wwp = a^(n+1)
×
576
    wwp > wp || throw(OverflowError("result is beyond the range of type of the base"))
×
577
    return wwp
×
578
end
579

580
"""
581
    prevpow(a, x)
582

583
The largest `a^n` not greater than `x`, where `n` is a non-negative integer.
584
`a` must be greater than 1, and `x` must not be less than 1.
585

586
See also [`nextpow`](@ref), [`isqrt`](@ref).
587

588
# Examples
589
```jldoctest
590
julia> prevpow(2, 7)
591
4
592

593
julia> prevpow(2, 9)
594
8
595

596
julia> prevpow(5, 20)
597
5
598

599
julia> prevpow(4, 16)
600
16
601
```
602
"""
603
function prevpow(a::T, x::Real) where T <: Real
×
604
    x < 1 && throw(DomainError(x, "`x` must be ≥ 1."))
×
605
    # See comment in nextpos() for a == special case.
606
    a == 2 && isa(x, Integer) && return _prevpow2(x)
×
607
    a <= 1 && throw(DomainError(a, "`a` must be greater than 1."))
×
608
    n = floor(Integer,log(a, x))
×
609
    # round-off error of log can go either direction, so need some checks
610
    p = a^n
×
611
    x > typemax(p) && throw(DomainError(x,"argument is beyond the range of type of the base"))
×
612
    if a isa Integer
×
613
        wp, overflow = mul_with_overflow(a, p)
×
614
        wp <= x && !overflow && return wp
×
615
    else
616
        wp = a^(n+1)
×
617
        wp <= x && return wp
×
618
    end
619
    p <= x && return p
×
620
    return a^(n-1)
×
621
end
622

623
## ndigits (number of digits) in base 10 ##
624

625
# decimal digits in an unsigned integer
626
const powers_of_ten = [
627
    0x0000000000000001, 0x000000000000000a, 0x0000000000000064, 0x00000000000003e8,
628
    0x0000000000002710, 0x00000000000186a0, 0x00000000000f4240, 0x0000000000989680,
629
    0x0000000005f5e100, 0x000000003b9aca00, 0x00000002540be400, 0x000000174876e800,
630
    0x000000e8d4a51000, 0x000009184e72a000, 0x00005af3107a4000, 0x00038d7ea4c68000,
631
    0x002386f26fc10000, 0x016345785d8a0000, 0x0de0b6b3a7640000, 0x8ac7230489e80000,
632
]
633
function bit_ndigits0z(x::Base.BitUnsigned64)
634
    lz = top_set_bit(x)
18✔
635
    nd = (1233*lz)>>12+1
18✔
636
    nd -= x < powers_of_ten[nd]
20✔
637
end
638
function bit_ndigits0z(x::UInt128)
639
    n = 0
×
640
    while x > 0x8ac7230489e80000 # 10e18
×
641
        x = div(x,0x8ac7230489e80000)
×
642
        n += 19
×
643
    end
×
644
    return n + ndigits0z(UInt64(x))
×
645
end
646

647
ndigits0z(x::BitSigned) = bit_ndigits0z(unsigned(abs(x)))
×
648
ndigits0z(x::BitUnsigned) = bit_ndigits0z(x)
×
649
ndigits0z(x::Integer) = ndigits0zpb(x, 10)
×
650

651
## ndigits with specified base ##
652

653
# The suffix "nb" stands for "negative base"
654
function ndigits0znb(x::Integer, b::Integer)
×
655
    d = 0
×
656
    if x isa Unsigned
×
657
        d += (x != 0)::Bool
×
658
        x = -signed(fld(x, -b))
×
659
    end
660
    # precondition: b < -1 && !(typeof(x) <: Unsigned)
661
    while x != 0
×
662
        x = cld(x,b)
×
663
        d += 1
×
664
    end
×
665
    return d
×
666
end
667

668
# do first division before conversion with signed here, which can otherwise overflow
669
ndigits0znb(x::Bool, b::Integer) = x % Int
×
670

671
# The suffix "pb" stands for "positive base"
672
function ndigits0zpb(x::Integer, b::Integer)
17✔
673
    # precondition: b > 1
674
    x == 0 && return 0
18✔
675
    b = Int(b)
1✔
676
    x = abs(x)
3✔
677
    if x isa Base.BitInteger
1✔
678
        x = unsigned(x)::Unsigned
3✔
679
        b == 2  && return top_set_bit(x)
18✔
680
        b == 8  && return (top_set_bit(x) + 2) ÷ 3
18✔
681
        b == 16 && return sizeof(x)<<1 - leading_zeros(x)>>2
18✔
682
        b == 10 && return bit_ndigits0z(x)
20✔
683
        if ispow2(b)
×
684
            dv, rm = divrem(top_set_bit(x), trailing_zeros(b))
×
685
            return iszero(rm) ? dv : dv + 1
×
686
        end
687
    end
688

689
    d = 0
×
690
    while x > typemax(Int)
×
691
        x = div(x,b)
×
692
        d += 1
×
693
    end
×
694
    x = div(x,b)
×
695
    d += 1
×
696

697
    m = 1
×
698
    while m <= x
×
699
        m *= b
×
700
        d += 1
×
701
    end
×
702
    return d
×
703
end
704

705
ndigits0zpb(x::Bool, b::Integer) = x % Int
×
706

707
# The suffix "0z" means that the output is 0 on input zero (cf. #16841)
708
"""
709
    ndigits0z(n::Integer, b::Integer=10)
710

711
Return 0 if `n == 0`, otherwise compute the number of digits in
712
integer `n` written in base `b` (i.e. equal to `ndigits(n, base=b)`
713
in this case).
714
The base `b` must not be in `[-1, 0, 1]`.
715

716
# Examples
717
```jldoctest
718
julia> Base.ndigits0z(0, 16)
719
0
720

721
julia> Base.ndigits(0, base=16)
722
1
723

724
julia> Base.ndigits0z(0)
725
0
726

727
julia> Base.ndigits0z(10, 2)
728
4
729

730
julia> Base.ndigits0z(10)
731
2
732
```
733

734
See also [`ndigits`](@ref).
735
"""
736
function ndigits0z(x::Integer, b::Integer)
1✔
737
    if b < -1
4,019✔
738
        ndigits0znb(x, b)
×
739
    elseif b > 1
4,019✔
740
        ndigits0zpb(x, b)
4,040✔
741
    else
742
        throw(DomainError(b, "The base must not be in `[-1, 0, 1]`."))
×
743
    end
744
end
745

746
# Extends the definition in base/int.jl
747
top_set_bit(x::Integer) = ceil(Integer, log2(x + oneunit(x)))
×
748

749
"""
750
    ndigits(n::Integer; base::Integer=10, pad::Integer=1)
751

752
Compute the number of digits in integer `n` written in base `base`
753
(`base` must not be in `[-1, 0, 1]`), optionally padded with zeros
754
to a specified size (the result will never be less than `pad`).
755

756
See also [`digits`](@ref), [`count_ones`](@ref).
757

758
# Examples
759
```jldoctest
760
julia> ndigits(0)
761
1
762

763
julia> ndigits(12345)
764
5
765

766
julia> ndigits(1022, base=16)
767
3
768

769
julia> string(1022, base=16)
770
"3fe"
771

772
julia> ndigits(123, pad=5)
773
5
774

775
julia> ndigits(-123)
776
3
777
```
778
"""
779
ndigits(x::Integer; base::Integer=10, pad::Integer=1) = max(pad, ndigits0z(x, base))
8,142✔
780

781
## integer to string functions ##
782

783
function bin(x::Unsigned, pad::Int, neg::Bool)
×
784
    m = top_set_bit(x)
×
785
    n = neg + max(pad, m)
×
786
    a = StringMemory(n)
×
787
    # for i in 0x0:UInt(n-1) # automatic vectorization produces redundant codes
788
    #     @inbounds a[n - i] = 0x30 + (((x >> i) % UInt8)::UInt8 & 0x1)
789
    # end
790
    i = n
×
791
    @inbounds while i >= 4
×
792
        b = UInt32((x % UInt8)::UInt8)
×
793
        d = 0x30303030 + ((b * 0x08040201) >> 0x3) & 0x01010101
×
794
        a[i-3] = (d >> 0x00) % UInt8
×
795
        a[i-2] = (d >> 0x08) % UInt8
×
796
        a[i-1] = (d >> 0x10) % UInt8
×
797
        a[i]   = (d >> 0x18) % UInt8
×
798
        x >>= 0x4
×
799
        i -= 4
×
800
    end
×
801
    while i > neg
×
802
        @inbounds a[i] = 0x30 + ((x % UInt8)::UInt8 & 0x1)
×
803
        x >>= 0x1
×
804
        i -= 1
×
805
    end
×
806
    neg && (@inbounds a[1] = 0x2d) # UInt8('-')
×
807
    unsafe_takestring(a)
×
808
end
809

810
function oct(x::Unsigned, pad::Int, neg::Bool)
×
811
    m = div(top_set_bit(x) + 2, 3)
×
812
    n = neg + max(pad, m)
×
813
    a = StringMemory(n)
×
814
    i = n
×
815
    while i > neg
×
816
        @inbounds a[i] = 0x30 + ((x % UInt8)::UInt8 & 0x7)
×
817
        x >>= 0x3
×
818
        i -= 1
×
819
    end
×
820
    neg && (@inbounds a[1] = 0x2d) # UInt8('-')
×
821
    unsafe_takestring(a)
×
822
end
823

824
# 2-digit decimal characters ("00":"99")
825
const _dec_d100 = UInt16[
826
# generating expression: UInt16[(0x30 + i % 10) << 0x8 + (0x30 + i ÷ 10) for i = 0:99]
827
#    0 0,    0 1,    0 2,    0 3, and so on in little-endian
828
  0x3030, 0x3130, 0x3230, 0x3330, 0x3430, 0x3530, 0x3630, 0x3730, 0x3830, 0x3930,
829
  0x3031, 0x3131, 0x3231, 0x3331, 0x3431, 0x3531, 0x3631, 0x3731, 0x3831, 0x3931,
830
  0x3032, 0x3132, 0x3232, 0x3332, 0x3432, 0x3532, 0x3632, 0x3732, 0x3832, 0x3932,
831
  0x3033, 0x3133, 0x3233, 0x3333, 0x3433, 0x3533, 0x3633, 0x3733, 0x3833, 0x3933,
832
  0x3034, 0x3134, 0x3234, 0x3334, 0x3434, 0x3534, 0x3634, 0x3734, 0x3834, 0x3934,
833
  0x3035, 0x3135, 0x3235, 0x3335, 0x3435, 0x3535, 0x3635, 0x3735, 0x3835, 0x3935,
834
  0x3036, 0x3136, 0x3236, 0x3336, 0x3436, 0x3536, 0x3636, 0x3736, 0x3836, 0x3936,
835
  0x3037, 0x3137, 0x3237, 0x3337, 0x3437, 0x3537, 0x3637, 0x3737, 0x3837, 0x3937,
836
  0x3038, 0x3138, 0x3238, 0x3338, 0x3438, 0x3538, 0x3638, 0x3738, 0x3838, 0x3938,
837
  0x3039, 0x3139, 0x3239, 0x3339, 0x3439, 0x3539, 0x3639, 0x3739, 0x3839, 0x3939
838
]
839

840
function append_c_digits(olength::Int, digits::Unsigned, buf, pos::Int)
18✔
841
    i = olength
×
842
    while i >= 2
27✔
843
        d, c = divrem(digits, 0x64)
9✔
844
        digits = oftype(digits, d)
×
845
        @inbounds d100 = _dec_d100[(c % Int) + 1]
9✔
846
        @inbounds buf[pos + i - 2] = d100 % UInt8
9✔
847
        @inbounds buf[pos + i - 1] = (d100 >> 0x8) % UInt8
9✔
848
        i -= 2
9✔
849
    end
9✔
850
    if i == 1
18✔
851
        @inbounds buf[pos] = UInt8('0') + rem(digits, 0xa) % UInt8
14✔
852
        i -= 1
×
853
    end
854
    return pos + olength
18✔
855
end
856

857
function append_nine_digits(digits::Unsigned, buf, pos::Int)
×
858
    if digits == 0
×
859
        for _ = 1:9
×
860
            @inbounds buf[pos] = UInt8('0')
×
861
            pos += 1
×
862
        end
×
863
        return pos
×
864
    end
865
    return @inline append_c_digits(9, digits, buf, pos) # force loop-unrolling on the length
×
866
end
867

868
function append_c_digits_fast(olength::Int, digits::Unsigned, buf, pos::Int)
18✔
869
    i = olength
×
870
    # n.b. olength may be larger than required to print all of `digits` (and will be padded
871
    # with zeros), but the printed number will be undefined if it is smaller, and may include
872
    # bits of both the high and low bytes.
873
    maxpow10 = 0x3b9aca00 # 10e9 as UInt32
×
874
    while i > 9 && digits > typemax(UInt)
18✔
875
        # do everything in cheap math chunks, using the processor's native math size
876
        d, c = divrem(digits, maxpow10)
×
877
        digits = oftype(digits, d)
×
878
        append_nine_digits(c % UInt32, buf, pos + i - 9)
×
879
        i -= 9
×
880
    end
×
881
    append_c_digits(i, digits % UInt, buf, pos)
18✔
882
    return pos + olength
18✔
883
end
884

885

886
function dec(x::Unsigned, pad::Int, neg::Bool)
15✔
887
    n = neg + ndigits(x, pad=pad)
18✔
888
    a = StringMemory(n)
18✔
889
    append_c_digits_fast(n, x, a, 1)
18✔
890
    neg && (@inbounds a[1] = 0x2d) # UInt8('-')
16✔
891
    unsafe_takestring(a)
21✔
892
end
893

894
function hex(x::Unsigned, pad::Int, neg::Bool)
1✔
895
    m = 2 * sizeof(x) - (leading_zeros(x) >> 2)
1✔
896
    n = neg + max(pad, m)
1✔
897
    a = StringMemory(n)
1✔
898
    i = n
×
899
    while i >= 2
2✔
900
        b = (x % UInt8)::UInt8
1✔
901
        d1, d2 = b >> 0x4, b & 0xf
1✔
902
        @inbounds a[i-1] = d1 + ifelse(d1 > 0x9, 0x57, 0x30)
1✔
903
        @inbounds a[i]   = d2 + ifelse(d2 > 0x9, 0x57, 0x30)
1✔
904
        x >>= 0x8
1✔
905
        i -= 2
1✔
906
    end
1✔
907
    if i > neg
1✔
908
        d = (x % UInt8)::UInt8 & 0xf
×
909
        @inbounds a[i] = d + ifelse(d > 0x9, 0x57, 0x30)
×
910
    end
911
    neg && (@inbounds a[1] = 0x2d) # UInt8('-')
1✔
912
    unsafe_takestring(a)
1✔
913
end
914

915
const base36digits = UInt8['0':'9';'a':'z']
916
const base62digits = UInt8['0':'9';'A':'Z';'a':'z']
917

918
function _base(base::Integer, x::Integer, pad::Int, neg::Bool)
×
919
    (x >= 0) | (base < 0) || throw(DomainError(x, "For negative `x`, `base` must be negative."))
×
920
    2 <= abs(base) <= 62 || throw(DomainError(base, "base must satisfy 2 ≤ abs(base) ≤ 62"))
×
921
    b = (base % Int)::Int
×
922
    digits = abs(b) <= 36 ? base36digits : base62digits
×
923
    n = neg + ndigits(x, base=b, pad=pad)
×
924
    a = StringMemory(n)
×
925
    i = n
×
926
    @inbounds while i > neg
×
927
        if b > 0
×
928
            a[i] = digits[1 + (rem(x, b) % Int)::Int]
×
929
            x = div(x,b)
×
930
        else
931
            a[i] = digits[1 + (mod(x, -b) % Int)::Int]
×
932
            x = cld(x,b)
×
933
        end
934
        i -= 1
×
935
    end
×
936
    neg && (@inbounds a[1] = 0x2d) # UInt8('-')
×
937
    unsafe_takestring(a)
×
938
end
939

940
split_sign(n::Integer) = unsigned(abs(n)), n < 0
17✔
941
split_sign(n::Unsigned) = n, false
×
942

943
"""
944
    string(n::Integer; base::Integer = 10, pad::Integer = 1)
945

946
Convert an integer `n` to a string in the given `base`,
947
optionally specifying a number of digits to pad to.
948

949
See also [`digits`](@ref), [`bitstring`](@ref), [`count_zeros`](@ref).
950

951
# Examples
952
```jldoctest
953
julia> string(5, base = 13, pad = 4)
954
"0005"
955

956
julia> string(-13, base = 5, pad = 4)
957
"-0023"
958
```
959
"""
960
function string(n::Integer; base::Integer = 10, pad::Integer = 1)
5,851✔
961
    pad = (min(max(pad, typemin(Int)), typemax(Int)) % Int)::Int
17✔
962
    if base == 2
17✔
963
        (n_positive, neg) = split_sign(n)
×
964
        bin(n_positive, pad, neg)
×
965
    elseif base == 8
17✔
966
        (n_positive, neg) = split_sign(n)
×
967
        oct(n_positive, pad, neg)
×
968
    elseif base == 10
17✔
969
        (n_positive, neg) = split_sign(n)
16✔
970
        dec(n_positive, pad, neg)
20✔
971
    elseif base == 16
1✔
972
        (n_positive, neg) = split_sign(n)
1✔
973
        hex(n_positive, pad, neg)
1✔
974
    else
975
        _base(base, base > 0 ? unsigned(abs(n)) : convert(Signed, n), pad, (base>0) & (n<0))
×
976
    end
977
end
978

979
string(b::Bool) = b ? "true" : "false"
62✔
980

981
"""
982
    bitstring(n)
983

984
A string giving the literal bit representation of a primitive type
985
(in bigendian order, i.e. most-significant bit first).
986

987
See also [`count_ones`](@ref), [`count_zeros`](@ref), [`digits`](@ref).
988

989
# Examples
990
```jldoctest
991
julia> bitstring(Int32(4))
992
"00000000000000000000000000000100"
993

994
julia> bitstring(2.2)
995
"0100000000000001100110011001100110011001100110011001100110011010"
996
```
997
"""
998
function bitstring(x::T) where {T}
×
999
    isprimitivetype(T) || throw(ArgumentError(LazyString(T, " not a primitive type")))
×
1000
    sz = sizeof(T) * 8
×
1001
    str = StringMemory(sz)
×
1002
    i = sz
×
1003
    @inbounds while i >= 4
×
1004
        b = UInt32(sizeof(T) == 1 ? bitcast(UInt8, x) : trunc_int(UInt8, x))
×
1005
        d = 0x30303030 + ((b * 0x08040201) >> 0x3) & 0x01010101
×
1006
        str[i-3] = (d >> 0x00) % UInt8
×
1007
        str[i-2] = (d >> 0x08) % UInt8
×
1008
        str[i-1] = (d >> 0x10) % UInt8
×
1009
        str[i]   = (d >> 0x18) % UInt8
×
1010
        x = lshr_int(x, 4)
×
1011
        i -= 4
×
1012
    end
×
1013
    return unsafe_takestring(str)
×
1014
end
1015

1016
"""
1017
    digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1)
1018

1019
Return an array with element type `T` (default `Int`) of the digits of `n` in the given
1020
base, optionally padded with zeros to a specified size. More significant digits are at
1021
higher indices, such that `n == sum(digits[k]*base^(k-1) for k in 1:length(digits))`.
1022

1023
See also [`ndigits`](@ref), [`digits!`](@ref),
1024
and for base 2 also [`bitstring`](@ref), [`count_ones`](@ref).
1025

1026
# Examples
1027
```jldoctest
1028
julia> digits(10)
1029
2-element Vector{Int64}:
1030
 0
1031
 1
1032

1033
julia> digits(10, base = 2)
1034
4-element Vector{Int64}:
1035
 0
1036
 1
1037
 0
1038
 1
1039

1040
julia> digits(-256, base = 10, pad = 5)
1041
5-element Vector{Int64}:
1042
 -6
1043
 -5
1044
 -2
1045
  0
1046
  0
1047

1048
julia> n = rand(-999:999);
1049

1050
julia> n == evalpoly(13, digits(n, base = 13))
1051
true
1052
```
1053
"""
1054
digits(n::Integer; base::Integer = 10, pad::Integer = 1) =
×
1055
    digits(typeof(base), n, base = base, pad = pad)
1056

1057
function digits(T::Type{<:Integer}, n::Integer; base::Integer = 10, pad::Integer = 1)
×
1058
    digits!(zeros(T, ndigits(n, base=base, pad=pad)), n, base=base)
×
1059
end
1060

1061
"""
1062
    hastypemax(T::Type) -> Bool
1063

1064
Return `true` if and only if the extrema `typemax(T)` and `typemin(T)` are defined.
1065
"""
1066
hastypemax(::Base.BitIntegerType) = true
×
1067
hastypemax(::Type{Bool}) = true
×
1068
hastypemax(::Type{T}) where {T} = applicable(typemax, T) && applicable(typemin, T)
×
1069

1070
"""
1071
    digits!(array, n::Integer; base::Integer = 10)
1072

1073
Fills an array of the digits of `n` in the given base. More significant digits are at higher
1074
indices. If the array length is insufficient, the least significant digits are filled up to
1075
the array length. If the array length is excessive, the excess portion is filled with zeros.
1076

1077
# Examples
1078
```jldoctest
1079
julia> digits!([2, 2, 2, 2], 10, base = 2)
1080
4-element Vector{Int64}:
1081
 0
1082
 1
1083
 0
1084
 1
1085

1086
julia> digits!([2, 2, 2, 2, 2, 2], 10, base = 2)
1087
6-element Vector{Int64}:
1088
 0
1089
 1
1090
 0
1091
 1
1092
 0
1093
 0
1094
```
1095
"""
1096
function digits!(a::AbstractVector{T}, n::Integer; base::Integer = 10) where T<:Integer
×
1097
    2 <= abs(base) || throw(DomainError(base, "base must be ≥ 2 or ≤ -2"))
×
1098
    hastypemax(T) && abs(base) - 1 > typemax(T) &&
×
1099
        throw(ArgumentError(LazyString("type ", T, " too small for base ", base)))
1100
    isempty(a) && return a
×
1101

1102
    if base > 0
×
1103
        if ispow2(base) && n >= 0 && n isa Base.BitInteger && base <= typemax(Int)
×
1104
            base = Int(base)
×
1105
            k = trailing_zeros(base)
×
1106
            c = base - 1
×
1107
            for i in eachindex(a)
×
1108
                a[i] = (n >> (k * (i - firstindex(a)))) & c
×
1109
            end
×
1110
        else
1111
            for i in eachindex(a)
×
1112
                n, d = divrem(n, base)
×
1113
                a[i] = d
×
1114
            end
×
1115
        end
1116
    else
1117
        # manually peel one loop iteration for type stability
1118
        n, d = fldmod(n, -base)
×
1119
        a[firstindex(a)] = d
×
1120
        n = -signed(n)
×
1121
        for i in firstindex(a)+1:lastindex(a)
×
1122
            n, d = fldmod(n, -base)
×
1123
            a[i] = d
×
1124
            n = -n
×
1125
        end
×
1126
    end
1127
    return a
×
1128
end
1129

1130
"""
1131
    isqrt(n::Integer)
1132

1133
Integer square root: the largest integer `m` such that `m*m <= n`.
1134

1135
```jldoctest
1136
julia> isqrt(5)
1137
2
1138
```
1139
"""
1140
isqrt(x::Integer) = oftype(x, trunc(sqrt(x)))
×
1141

1142
function isqrt(x::Union{Int64,UInt64,Int128,UInt128})
×
1143
    x==0 && return x
×
1144
    s = oftype(x, trunc(sqrt(x)))
×
1145
    # fix with a Newton iteration, since conversion to float discards
1146
    # too many bits.
1147
    s = (s + div(x,s)) >> 1
×
1148
    s*s > x ? s-1 : s
×
1149
end
1150

1151
"""
1152
    factorial(n::Integer)
1153

1154
Factorial of `n`. If `n` is an [`Integer`](@ref), the factorial is computed as an
1155
integer (promoted to at least 64 bits). Note that this may overflow if `n` is not small,
1156
but you can use `factorial(big(n))` to compute the result exactly in arbitrary precision.
1157

1158
See also [`binomial`](@ref).
1159

1160
# Examples
1161
```jldoctest
1162
julia> factorial(6)
1163
720
1164

1165
julia> factorial(21)
1166
ERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` instead
1167
Stacktrace:
1168
[...]
1169

1170
julia> factorial(big(21))
1171
51090942171709440000
1172
```
1173

1174
# External links
1175
* [Factorial](https://en.wikipedia.org/wiki/Factorial) on Wikipedia.
1176
"""
1177
function factorial(n::Integer)
×
1178
    n < 0 && throw(DomainError(n, "`n` must be non-negative."))
×
1179
    f::typeof(n*n) = 1
×
1180
    for i::typeof(n*n) = 2:n
×
1181
        f *= i
×
1182
    end
×
1183
    return f
×
1184
end
1185

1186
"""
1187
    binomial(n::Integer, k::Integer)
1188

1189
The _binomial coefficient_ ``\\binom{n}{k}``, being the coefficient of the ``k``th term in
1190
the polynomial expansion of ``(1+x)^n``.
1191

1192
If ``n`` is non-negative, then it is the number of ways to choose `k` out of `n` items:
1193
```math
1194
\\binom{n}{k} = \\frac{n!}{k! (n-k)!}
1195
```
1196
where ``n!`` is the [`factorial`](@ref) function.
1197

1198
If ``n`` is negative, then it is defined in terms of the identity
1199
```math
1200
\\binom{n}{k} = (-1)^k \\binom{k-n-1}{k}
1201
```
1202

1203
See also [`factorial`](@ref).
1204

1205
# Examples
1206
```jldoctest
1207
julia> binomial(5, 3)
1208
10
1209

1210
julia> factorial(5) ÷ (factorial(5-3) * factorial(3))
1211
10
1212

1213
julia> binomial(-5, 3)
1214
-35
1215
```
1216

1217
# External links
1218
* [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.
1219
"""
1220
binomial(n::Integer, k::Integer) = binomial(promote(n, k)...)
×
1221

1222
Base.@assume_effects :terminates_locally function binomial(n::T, k::T) where T<:Integer
×
1223
    n0, k0 = n, k
×
1224
    k < 0 && return zero(T)
×
1225
    sgn = one(T)
×
1226
    if n < 0
×
1227
        n = -n + k - one(T)
×
1228
        if isodd(k)
×
1229
            sgn = -sgn
×
1230
        end
1231
    end
1232
    k > n && return zero(T)
×
1233
    (k == 0 || k == n) && return sgn
×
1234
    k == 1 && return sgn*n
×
1235
    if k > (n>>1)
×
1236
        k = (n - k)
×
1237
    end
1238
    x = nn = n - k + one(T)
×
1239
    nn += one(T)
×
1240
    rr = T(2)
×
1241
    while rr <= k
×
1242
        xt = div(widemul(x, nn), rr)
×
1243
        x = xt % T
×
1244
        x == xt || throw(OverflowError(LazyString("binomial(", n0, ", ", k0, ") overflows")))
×
1245
        rr += one(T)
×
1246
        nn += one(T)
×
1247
    end
×
1248
    copysign(x, sgn)
×
1249
end
1250

1251
"""
1252
    binomial(x::Number, k::Integer)
1253

1254
The generalized binomial coefficient, defined for `k ≥ 0` by
1255
the polynomial
1256
```math
1257
\\frac{1}{k!} \\prod_{j=0}^{k-1} (x - j)
1258
```
1259
When `k < 0` it returns zero.
1260

1261
For the case of integer `x`, this is equivalent to the ordinary
1262
integer binomial coefficient
1263
```math
1264
\\binom{n}{k} = \\frac{n!}{k! (n-k)!}
1265
```
1266

1267
Further generalizations to non-integer `k` are mathematically possible, but
1268
involve the Gamma function and/or the beta function, which are
1269
not provided by the Julia standard library but are available
1270
in external packages such as [SpecialFunctions.jl](https://github.com/JuliaMath/SpecialFunctions.jl).
1271

1272
# External links
1273
* [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.
1274
"""
1275
function binomial(x::Number, k::Integer)
×
1276
    k < 0 && return zero(x)/one(k)
×
1277
    # we don't use prod(i -> (x-i+1), 1:k) / factorial(k),
1278
    # and instead divide each term by i, to avoid spurious overflow.
1279
    return prod(i -> (x-(i-1))/i, OneTo(k), init=oneunit(x)/one(k))
×
1280
end
1281

1282
"""
1283
    clamp(x, lo, hi)
1284

1285
Return `x` if `lo <= x <= hi`. If `x > hi`, return `hi`. If `x < lo`, return `lo`. Arguments
1286
are promoted to a common type.
1287

1288
See also [`clamp!`](@ref), [`min`](@ref), [`max`](@ref).
1289

1290
!!! compat "Julia 1.3"
1291
    `missing` as the first argument requires at least Julia 1.3.
1292

1293
# Examples
1294
```jldoctest
1295
julia> clamp.([pi, 1.0, big(10)], 2.0, 9.0)
1296
3-element Vector{BigFloat}:
1297
 3.141592653589793238462643383279502884197169399375105820974944592307816406286198
1298
 2.0
1299
 9.0
1300

1301
julia> clamp.([11, 8, 5], 10, 6)  # an example where lo > hi
1302
3-element Vector{Int64}:
1303
  6
1304
  6
1305
 10
1306
```
1307
"""
1308
function clamp(x::X, lo::L, hi::H) where {X,L,H}
1309
    T = promote_type(X, L, H)
×
1310
    return (x > hi) ? convert(T, hi) : (x < lo) ? convert(T, lo) : convert(T, x)
14✔
1311
end
1312

1313
"""
1314
    clamp(x, T)::T
1315

1316
Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`.
1317

1318
See also [`trunc`](@ref).
1319

1320
# Examples
1321
```jldoctest
1322
julia> clamp(200, Int8)
1323
127
1324

1325
julia> clamp(-200, Int8)
1326
-128
1327

1328
julia> trunc(Int, 4pi^2)
1329
39
1330
```
1331
"""
1332
function clamp(x, ::Type{T}) where {T<:Integer}
1333
    # delegating to clamp(x, typemin(T), typemax(T)) would promote types
1334
    # this way, we avoid unnecessary conversions
1335
    # think of, e.g., clamp(big(2) ^ 200, Int16)
1336
    lo = typemin(T)
×
1337
    hi = typemax(T)
×
1338
    return (x > hi) ? hi : (x < lo) ? lo : convert(T, x)
×
1339
end
1340

1341

1342
"""
1343
    clamp!(array::AbstractArray, lo, hi)
1344

1345
Restrict values in `array` to the specified range, in-place.
1346
See also [`clamp`](@ref).
1347

1348
!!! compat "Julia 1.3"
1349
    `missing` entries in `array` require at least Julia 1.3.
1350

1351
# Examples
1352
```jldoctest
1353
julia> row = collect(-4:4)';
1354

1355
julia> clamp!(row, 0, Inf)
1356
1×9 adjoint(::Vector{Int64}) with eltype Int64:
1357
 0  0  0  0  0  1  2  3  4
1358

1359
julia> clamp.((-4:4)', 0, Inf)
1360
1×9 Matrix{Float64}:
1361
 0.0  0.0  0.0  0.0  0.0  1.0  2.0  3.0  4.0
1362
```
1363
"""
1364
function clamp!(x::AbstractArray, lo, hi)
×
1365
    @inbounds for i in eachindex(x)
×
1366
        x[i] = clamp(x[i], lo, hi)
×
1367
    end
×
1368
    x
×
1369
end
1370

1371
"""
1372
    clamp(x::Integer, r::AbstractUnitRange)
1373

1374
Clamp `x` to lie within range `r`.
1375

1376
!!! compat "Julia 1.6"
1377
     This method requires at least Julia 1.6.
1378
"""
1379
clamp(x::Integer, r::AbstractUnitRange{<:Integer}) = clamp(x, first(r), last(r))
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc