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

JuliaLang / julia / #37527

pending completion
#37527

push

local

web-flow
make `IRShow.method_name` inferrable (#49607)

18 of 18 new or added lines in 3 files covered. (100.0%)

68710 of 81829 relevant lines covered (83.97%)

33068903.12 hits per line

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

94.67
/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
97✔
42
    while b != 0
97✔
43
        t = b
65✔
44
        b = rem(a, b)
65✔
45
        a = t
65✔
46
    end
65✔
47
    checked_abs(a)
97✔
48
end
49

50
function gcd(a::T, b::T) where T<:BitInteger
2,239,711✔
51
    a == 0 && return Base.checked_abs(b)
2,244,093✔
52
    b == 0 && return Base.checked_abs(a)
2,174,298✔
53
    if a isa Signed && a == typemin(T)
2,148,551✔
54
        if a == b
31✔
55
            Base.__throw_gcd_overflow(a, b)
10✔
56
        else
57
            a, b = b, a
13✔
58
        end
59
    end
60
    return _gcd(a, b)
2,148,541✔
61
end
62
@noinline __throw_gcd_overflow(a, b) =
10✔
63
    throw(OverflowError(LazyString("gcd(", a, ", ", b, ") overflows")))
64

65
function absdiff(x::T,y::T) where {T<:Unsigned}
6,501✔
66
    d = max(x,y) - min(x,y)
6,501✔
67
    d, d
6,501✔
68
end
69
function absdiff(x::T,y::T) where {T<:Signed}
19,961✔
70
    d = x - y
5,654,312✔
71
    abs(d), d
5,654,312✔
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
10,299✔
78
    zb = trailing_zeros(bin)
2,148,541✔
79
    za = trailing_zeros(ain)
2,148,541✔
80
    a = abs(ain)
2,148,541✔
81
    b = abs(bin >> zb)
2,148,541✔
82
    k = min(za, zb)
2,148,541✔
83
    while a != 0
7,809,354✔
84
        a >>= za
5,660,813✔
85
        absd, diff = absdiff(a, b)
5,660,813✔
86
        za = trailing_zeros(diff)
5,660,813✔
87
        b = min(a, b)
5,660,813✔
88
        a = absd
26,463✔
89
    end
5,660,813✔
90
    r = b << k
2,148,541✔
91
    return r % T
2,148,541✔
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
!!! compat "Julia 1.4"
101
    Rational arguments require Julia 1.4 or later.
102

103
# Examples
104
```jldoctest
105
julia> lcm(2, 3)
106
6
107

108
julia> lcm(-2, 3)
109
6
110

111
julia> lcm(0, 3)
112
0
113

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

117
julia> lcm(1//3, 2//3)
118
2//3
119

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

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

126
julia> lcm(1, 3, 5, 7)
127
105
128
```
129
"""
130
function lcm(a::T, b::T) where T<:Integer
8,873✔
131
    # explicit a==0 test is to handle case of lcm(0, 0) correctly
132
    # explicit b==0 test is to handle case of lcm(typemin(T),0) correctly
133
    if a == 0 || b == 0
17,353✔
134
        return zero(a)
706✔
135
    else
136
        return checked_abs(checked_mul(a, div(b, gcd(b,a))))
8,167✔
137
    end
138
end
139

140
gcd(a::Integer) = checked_abs(a)
40✔
141
gcd(a::Rational) = checked_abs(a.num) // a.den
10✔
142
lcm(a::Union{Integer,Rational}) = gcd(a)
30✔
143
gcd(a::Unsigned, b::Signed) = gcd(promote(a, abs(b))...)
248✔
144
gcd(a::Signed, b::Unsigned) = gcd(promote(abs(a), b)...)
×
145
gcd(a::Real, b::Real) = gcd(promote(a,b)...)
148✔
146
lcm(a::Real, b::Real) = lcm(promote(a,b)...)
35✔
147
gcd(a::Real, b::Real, c::Real...) = gcd(a, gcd(b, c...))
40✔
148
lcm(a::Real, b::Real, c::Real...) = lcm(a, lcm(b, c...))
50✔
149
gcd(a::T, b::T) where T<:Real = throw(MethodError(gcd, (a,b)))
1✔
150
lcm(a::T, b::T) where T<:Real = throw(MethodError(lcm, (a,b)))
1✔
151

152
gcd(abc::AbstractArray{<:Real}) = reduce(gcd, abc; init=zero(eltype(abc)))
11✔
153
lcm(abc::AbstractArray{<:Real}) = reduce(lcm, abc; init=one(eltype(abc)))
86✔
154

155
function gcd(abc::AbstractArray{<:Integer})
85✔
156
    a = zero(eltype(abc))
85✔
157
    for b in abc
95✔
158
        a = gcd(a, b)
203✔
159
        if a == 1
165✔
160
            return a
20✔
161
        end
162
    end
200✔
163
    return a
65✔
164
end
165

166
# return (gcd(a, b), x, y) such that ax+by == gcd(a, b)
167
"""
168
    gcdx(a, b)
169

170
Computes the greatest common (positive) divisor of `a` and `b` and their Bézout
171
coefficients, i.e. the integer coefficients `u` and `v` that satisfy
172
``ua+vb = d = gcd(a, b)``. ``gcdx(a, b)`` returns ``(d, u, v)``.
173

174
The arguments may be integer and rational numbers.
175

176
!!! compat "Julia 1.4"
177
    Rational arguments require Julia 1.4 or later.
178

179
# Examples
180
```jldoctest
181
julia> gcdx(12, 42)
182
(6, -3, 1)
183

184
julia> gcdx(240, 46)
185
(2, -9, 47)
186
```
187

188
!!! note
189
    Bézout coefficients are *not* uniquely defined. `gcdx` returns the minimal
190
    Bézout coefficients that are computed by the extended Euclidean algorithm.
191
    (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.)
192
    For signed integers, these coefficients `u` and `v` are minimal in
193
    the sense that ``|u| < |b/d|`` and ``|v| < |a/d|``. Furthermore,
194
    the signs of `u` and `v` are chosen so that `d` is positive.
195
    For unsigned integers, the coefficients `u` and `v` might be near
196
    their `typemax`, and the identity then holds only via the unsigned
197
    integers' modulo arithmetic.
198
"""
199
Base.@assume_effects :terminates_locally function gcdx(a::Integer, b::Integer)
267,940✔
200
    T = promote_type(typeof(a), typeof(b))
267,940✔
201
    # a0, b0 = a, b
202
    s0, s1 = oneunit(T), zero(T)
267,940✔
203
    t0, t1 = s1, s0
267,940✔
204
    # The loop invariant is: s0*a0 + t0*b0 == a && s1*a0 + t1*b0 == b
205
    x = a % T
267,940✔
206
    y = b % T
267,940✔
207
    while y != 0
1,450,113✔
208
        q, r = divrem(x, y)
1,182,175✔
209
        x, y = y, r
1,182,173✔
210
        s0, s1 = s1, s0 - q*s1
1,182,173✔
211
        t0, t1 = t1, t0 - q*t1
1,182,173✔
212
    end
1,182,173✔
213
    x < 0 ? (-x, -s0, -t0) : (x, s0, t0)
268,858✔
214
end
215
gcdx(a::Real, b::Real) = gcdx(promote(a,b)...)
12✔
216
gcdx(a::T, b::T) where T<:Real = throw(MethodError(gcdx, (a,b)))
1✔
217

218
# multiplicative inverse of n mod m, error if none
219

220
"""
221
    invmod(n, m)
222

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

227
# Examples
228
```jldoctest
229
julia> invmod(2, 5)
230
3
231

232
julia> invmod(2, 3)
233
2
234

235
julia> invmod(5, 6)
236
5
237
```
238
"""
239
function invmod(n::Integer, m::Integer)
134,526✔
240
    iszero(m) && throw(DomainError(m, "`m` must not be 0."))
134,526✔
241
    if n isa Signed && hastypemax(typeof(n))
133,932✔
242
        # work around inconsistencies in gcdx
243
        # https://github.com/JuliaLang/julia/issues/33781
244
        T = promote_type(typeof(n), typeof(m))
68,640✔
245
        n == typemin(typeof(n)) && m == typeof(n)(-1) && return T(0)
68,640✔
246
        n == typeof(n)(-1) && m == typemin(typeof(n)) && return T(-1)
68,639✔
247
    end
248
    g, x, y = gcdx(n, m)
134,820✔
249
    g != 1 && throw(DomainError((n, m), LazyString("Greatest common divisor is ", g, ".")))
133,930✔
250
    # Note that m might be negative here.
251
    if n isa Unsigned && hastypemax(typeof(n)) && x > typemax(n)>>1
81,691✔
252
        # x might have wrapped if it would have been negative
253
        # adding back m forces a correction
254
        x += m
19,571✔
255
    end
256
    # The postcondition is: mod(result * n, m) == mod(T(1), m) && div(result, m) == 0
257
    return mod(x, m)
81,691✔
258
end
259

260
# ^ for any x supporting *
261
to_power_type(x) = convert(Base._return_type(*, Tuple{typeof(x), typeof(x)}), x)
400,029,040✔
262
@noinline throw_domerr_powbysq(::Any, p) = throw(DomainError(p, LazyString(
1✔
263
    "Cannot raise an integer x to a negative power ", p, ".",
264
    "\nConvert input to float.")))
265
@noinline throw_domerr_powbysq(::Integer, p) = throw(DomainError(p, LazyString(
3✔
266
    "Cannot raise an integer x to a negative power ", p, ".",
267
    "\nMake x or ", p, " a float by adding a zero decimal ",
268
    "(e.g., 2.0^", p, " or 2^", float(p), " instead of 2^", p, ")",
269
    "or write 1/x^", -p, ", float(x)^", p, ", x^float(", p, ") or (x//1)^", p, ".")))
270
@noinline throw_domerr_powbysq(::AbstractMatrix, p) = throw(DomainError(p, LazyString(
×
271
    "Cannot raise an integer matrix x to a negative power ", p, ".",
272
    "\nMake x a float matrix by adding a zero decimal ",
273
    "(e.g., [2.0 1.0;1.0 0.0]^", p, " instead of [2 1;1 0]^", p, ")",
274
    "or write float(x)^", p, " or Rational.(x)^", p, ".")))
275
@assume_effects :terminates_locally function power_by_squaring(x_, p::Integer)
400,090,085✔
276
    x = to_power_type(x_)
400,034,057✔
277
    if p == 1
400,090,085✔
278
        return copy(x)
200,002,829✔
279
    elseif p == 0
200,087,256✔
280
        return one(x)
18,487✔
281
    elseif p == 2
200,068,769✔
282
        return x*x
200,003,824✔
283
    elseif p < 0
64,945✔
284
        isone(x) && return copy(x)
18✔
285
        isone(-x) && return iseven(p) ? one(x) : copy(x)
17✔
286
        throw_domerr_powbysq(x, p)
3✔
287
    end
288
    t = trailing_zeros(p) + 1
64,927✔
289
    p >>= t
64,927✔
290
    while (t -= 1) > 0
135,877✔
291
        x *= x
70,950✔
292
    end
70,950✔
293
    y = x
27,892✔
294
    while p > 0
617,130✔
295
        t = trailing_zeros(p) + 1
552,204✔
296
        p >>= t
552,204✔
297
        while (t -= 1) >= 0
1,130,477✔
298
            x *= x
578,274✔
299
        end
578,273✔
300
        y *= x
552,205✔
301
    end
552,203✔
302
    return y
64,926✔
303
end
304
power_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x)
5✔
305
function power_by_squaring(x::Bool, p::Integer)
16✔
306
    p < 0 && !x && throw_domerr_powbysq(x, p)
16✔
307
    return (p==0) | x
15✔
308
end
309

310
^(x::T, p::T) where {T<:Integer} = power_by_squaring(x,p)
60,007✔
311
^(x::Number, p::Integer)  = power_by_squaring(x,p)
13,650✔
312

313
# x^p for any literal integer p is lowered to Base.literal_pow(^, x, Val(p))
314
# to enable compile-time optimizations specialized to p.
315
# However, we still need a fallback that calls the function ^ which may either
316
# mean Base.^ or something else, depending on context.
317
# We mark these @inline since if the target is marked @inline,
318
# we want to make sure that gets propagated,
319
# even if it is over the inlining threshold.
320
@inline literal_pow(f, x, ::Val{p}) where {p} = f(x,p)
1✔
321

322
# Restrict inlining to hardware-supported arithmetic types, which
323
# are fast enough to benefit from inlining.
324
const HWReal = Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64,Float32,Float64}
325
const HWNumber = Union{HWReal, Complex{<:HWReal}, Rational{<:HWReal}}
326

327
# Inline x^2 and x^3 for Val
328
# (The first argument prevents unexpected behavior if a function ^
329
# is defined that is not equal to Base.^)
330
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{0}) = one(x)
1,222✔
331
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{1}) = x
12✔
332
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{2}) = x*x
410,847,104✔
333
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{3}) = x*x*x
400,012,254✔
334
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{-1}) = inv(x)
400,001,215✔
335
@inline literal_pow(::typeof(^), x::HWNumber, ::Val{-2}) = (i=inv(x); i*i)
50✔
336

337
# don't use the inv(x) transformation here since float^p is slightly more accurate
338
@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{p}) where {p} = x^p
33,911✔
339
@inline literal_pow(::typeof(^), x::AbstractFloat, ::Val{-1}) = inv(x)
3✔
340

341
# for other types, define x^-n as inv(x)^n so that negative literal powers can
342
# be computed in a type-stable way even for e.g. integers.
343
@inline function literal_pow(f::typeof(^), x, ::Val{p}) where {p}
320,039✔
344
    if p < 0
320,004✔
345
        if x isa BitInteger64
47✔
346
            f(Float64(x), p) # inv would cause rounding, while Float64^Integer is able to compensate the inverse
5✔
347
        else
348
            f(inv(x), -p)
42✔
349
        end
350
    else
351
        f(x, p)
319,992✔
352
    end
353
end
354

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

359
# b^p mod m
360

361
"""
362
    powermod(x::Integer, p::Integer, m)
363

364
Compute ``x^p \\pmod m``.
365

366
# Examples
367
```jldoctest
368
julia> powermod(2, 6, 5)
369
4
370

371
julia> mod(2^6, 5)
372
4
373

374
julia> powermod(5, 2, 20)
375
5
376

377
julia> powermod(5, 2, 19)
378
6
379

380
julia> powermod(5, 3, 19)
381
11
382
```
383
"""
384
function powermod(x::Integer, p::Integer, m::T) where T<:Integer
7,587✔
385
    p == 0 && return mod(one(m),m)
7,587✔
386
    # When the concrete type of p is signed and has the lowest value,
387
    # `p != 0 && p == -p` is equivalent to `p == typemin(typeof(p))` for 2's complement representation.
388
    # but will work for integer types like `BigInt` that don't have `typemin` defined
389
    # It needs special handling otherwise will cause overflow problem.
390
    if p == -p
6,322✔
391
        imod = invmod(x, m)
2✔
392
        rhalf = powermod(imod, -(p÷2), m)
2✔
393
        r::T = mod(widemul(rhalf, rhalf), m)
2✔
394
        isodd(p) && (r = mod(widemul(r, imod), m))
2✔
395
        #else odd
396
        return r
2✔
397
    elseif p < 0
6,320✔
398
        return powermod(invmod(x, m), -p, m)
7✔
399
    end
400
    (m == 1 || m == -1) && return zero(m)
6,313✔
401
    b = oftype(m,mod(x,m))  # this also checks for divide by zero
9,474✔
402

403
    t = prevpow(2, p)
5,682✔
404
    r = 1
5,682✔
405
    while true
12,746✔
406
        if p >= t
12,746✔
407
            r = mod(widemul(r,b),m)
7,954✔
408
            p -= t
7,954✔
409
        end
410
        t >>>= 1
12,746✔
411
        t <= 0 && break
12,746✔
412
        r = mod(widemul(r,r),m)
7,064✔
413
    end
7,064✔
414
    return r
5,682✔
415
end
416

417
# optimization: promote the modulus m to BigInt only once (cf. widemul in generic powermod above)
418
powermod(x::Integer, p::Integer, m::Union{Int128,UInt128}) = oftype(m, powermod(x, p, big(m)))
3,780✔
419

420
_nextpow2(x::Unsigned) = oneunit(x)<<(top_set_bit(x-oneunit(x)))
50,146✔
421
_nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_nextpow2(unsigned(-x)) : _nextpow2(unsigned(x)))
100,284✔
422
_prevpow2(x::Unsigned) = one(x) << unsigned(top_set_bit(x)-1)
5,795✔
423
_prevpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_prevpow2(unsigned(-x)) : _prevpow2(unsigned(x)))
11,580✔
424

425
"""
426
    ispow2(n::Number) -> Bool
427

428
Test whether `n` is an integer power of two.
429

430
See also [`count_ones`](@ref), [`prevpow`](@ref), [`nextpow`](@ref).
431

432
# Examples
433
```jldoctest
434
julia> ispow2(4)
435
true
436

437
julia> ispow2(5)
438
false
439

440
julia> ispow2(4.5)
441
false
442

443
julia> ispow2(0.25)
444
true
445

446
julia> ispow2(1//8)
447
true
448
```
449

450
!!! compat "Julia 1.6"
451
    Support for non-`Integer` arguments was added in Julia 1.6.
452
"""
453
ispow2(x::Number) = isreal(x) && ispow2(real(x))
4✔
454

455
ispow2(x::Integer) = x > 0 && count_ones(x) == 1
50,879✔
456

457
"""
458
    nextpow(a, x)
459

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

463
See also [`prevpow`](@ref).
464

465
# Examples
466
```jldoctest
467
julia> nextpow(2, 7)
468
8
469

470
julia> nextpow(2, 9)
471
16
472

473
julia> nextpow(5, 20)
474
25
475

476
julia> nextpow(4, 16)
477
16
478
```
479
"""
480
function nextpow(a::Real, x::Real)
50,279✔
481
    x <= 0 && throw(DomainError(x, "`x` must be positive."))
50,279✔
482
    # Special case fast path for x::Integer, a == 2.
483
    # This is a very common case. Constant prop will make sure that a call site
484
    # specified as `nextpow(2, x)` will get this special case inlined.
485
    a == 2 && isa(x, Integer) && return _nextpow2(x)
50,274✔
486
    a <= 1 && throw(DomainError(a, "`a` must be greater than 1."))
28✔
487
    x <= 1 && return one(a)
23✔
488
    n = ceil(Integer,log(a, x))
23✔
489
    # round-off error of log can go either direction, so need some checks
490
    p = a^(n-1)
29✔
491
    x > typemax(p) && throw(DomainError(x,"argument is beyond the range of type of the base"))
23✔
492
    p >= x && return p
22✔
493
    wp = a^n
28✔
494
    wp > p || throw(OverflowError("result is beyond the range of type of the base"))
23✔
495
    wp >= x && return wp
21✔
496
    wwp = a^(n+1)
9✔
497
    wwp > wp || throw(OverflowError("result is beyond the range of type of the base"))
6✔
498
    return wwp
6✔
499
end
500

501
"""
502
    prevpow(a, x)
503

504
The largest `a^n` not greater than `x`, where `n` is a non-negative integer.
505
`a` must be greater than 1, and `x` must not be less than 1.
506

507
See also [`nextpow`](@ref), [`isqrt`](@ref).
508

509
# Examples
510
```jldoctest
511
julia> prevpow(2, 7)
512
4
513

514
julia> prevpow(2, 9)
515
8
516

517
julia> prevpow(5, 20)
518
5
519

520
julia> prevpow(4, 16)
521
16
522
```
523
"""
524
function prevpow(a::T, x::Real) where T <: Real
5,919✔
525
    x < 1 && throw(DomainError(x, "`x` must be ≥ 1."))
5,919✔
526
    # See comment in nextpos() for a == special case.
527
    a == 2 && isa(x, Integer) && return _prevpow2(x)
5,917✔
528
    a <= 1 && throw(DomainError(a, "`a` must be greater than 1."))
20✔
529
    n = floor(Integer,log(a, x))
15✔
530
    # round-off error of log can go either direction, so need some checks
531
    p = a^n
22✔
532
    x > typemax(p) && throw(DomainError(x,"argument is beyond the range of type of the base"))
15✔
533
    if a isa Integer
14✔
534
        wp, overflow = mul_with_overflow(a, p)
7✔
535
        wp <= x && !overflow && return wp
7✔
536
    else
537
        wp = a^(n+1)
14✔
538
        wp <= x && return wp
7✔
539
    end
540
    p <= x && return p
13✔
541
    return a^(n-1)
7✔
542
end
543

544
## ndigits (number of digits) in base 10 ##
545

546
# decimal digits in an unsigned integer
547
const powers_of_ten = [
548
    0x0000000000000001, 0x000000000000000a, 0x0000000000000064, 0x00000000000003e8,
549
    0x0000000000002710, 0x00000000000186a0, 0x00000000000f4240, 0x0000000000989680,
550
    0x0000000005f5e100, 0x000000003b9aca00, 0x00000002540be400, 0x000000174876e800,
551
    0x000000e8d4a51000, 0x000009184e72a000, 0x00005af3107a4000, 0x00038d7ea4c68000,
552
    0x002386f26fc10000, 0x016345785d8a0000, 0x0de0b6b3a7640000, 0x8ac7230489e80000,
553
]
554
function bit_ndigits0z(x::Base.BitUnsigned64)
×
555
    lz = top_set_bit(x)
13,565,652✔
556
    nd = (1233*lz)>>12+1
13,596,716✔
557
    nd -= x < powers_of_ten[nd]
13,611,272✔
558
end
559
function bit_ndigits0z(x::UInt128)
79✔
560
    n = 0
×
561
    while x > 0x8ac7230489e80000
150✔
562
        x = div(x,0x8ac7230489e80000)
71✔
563
        n += 19
71✔
564
    end
71✔
565
    return n + ndigits0z(UInt64(x))
79✔
566
end
567

568
ndigits0z(x::BitSigned) = bit_ndigits0z(unsigned(abs(x)))
×
569
ndigits0z(x::BitUnsigned) = bit_ndigits0z(x)
79✔
570
ndigits0z(x::Integer) = ndigits0zpb(x, 10)
×
571

572
## ndigits with specified base ##
573

574
# The suffix "nb" stands for "negative base"
575
function ndigits0znb(x::Integer, b::Integer)
37✔
576
    d = 0
×
577
    if x isa Unsigned
15✔
578
        d += (x != 0)::Bool
15✔
579
        x = -signed(fld(x, -b))
15✔
580
    end
581
    # precondition: b < -1 && !(typeof(x) <: Unsigned)
582
    while x != 0
1,773✔
583
        x = cld(x,b)
1,454✔
584
        d += 1
1,416✔
585
    end
1,416✔
586
    return d
312✔
587
end
588

589
# do first division before conversion with signed here, which can otherwise overflow
590
ndigits0znb(x::Bool, b::Integer) = x % Int
76✔
591

592
# The suffix "pb" stands for "positive base"
593
function ndigits0zpb(x::Integer, b::Integer)
13,695,038✔
594
    # precondition: b > 1
595
    x == 0 && return 0
13,678,587✔
596
    b = Int(b)
6✔
597
    x = abs(x)
499,893✔
598
    if x isa Base.BitInteger
13,658,444✔
599
        x = unsigned(x)::Unsigned
499,893✔
600
        b == 2  && return top_set_bit(x)
13,650,844✔
601
        b == 8  && return (top_set_bit(x) + 2) ÷ 3
13,598,215✔
602
        b == 16 && return sizeof(x)<<1 - leading_zeros(x)>>2
13,573,958✔
603
        b == 10 && return bit_ndigits0z(x)
13,563,862✔
604
        if ispow2(b)
5,827✔
605
            dv, rm = divrem(top_set_bit(x), trailing_zeros(b))
252✔
606
            return iszero(rm) ? dv : dv + 1
252✔
607
        end
608
    end
609

610
    d = 0
5,575✔
611
    while x > typemax(Int)
23,079✔
612
        x = div(x,b)
16,402✔
613
        d += 1
16,402✔
614
    end
16,402✔
615
    x = div(x,b)
6,677✔
616
    d += 1
5,575✔
617

618
    m = 1
×
619
    while m <= x
45,924✔
620
        m *= b
40,349✔
621
        d += 1
40,349✔
622
    end
40,349✔
623
    return d
5,575✔
624
end
625

626
ndigits0zpb(x::Bool, b::Integer) = x % Int
76✔
627

628
# The suffix "0z" means that the output is 0 on input zero (cf. #16841)
629
"""
630
    ndigits0z(n::Integer, b::Integer=10)
631

632
Return 0 if `n == 0`, otherwise compute the number of digits in
633
integer `n` written in base `b` (i.e. equal to `ndigits(n, base=b)`
634
in this case).
635
The base `b` must not be in `[-1, 0, 1]`.
636

637
# Examples
638
```jldoctest
639
julia> Base.ndigits0z(0, 16)
640
0
641

642
julia> Base.ndigits(0, base=16)
643
1
644

645
julia> Base.ndigits0z(0)
646
0
647

648
julia> Base.ndigits0z(10, 2)
649
4
650

651
julia> Base.ndigits0z(10)
652
2
653
```
654

655
See also [`ndigits`](@ref).
656
"""
657
function ndigits0z(x::Integer, b::Integer)
555,657✔
658
    if b < -1
562,503✔
659
        ndigits0znb(x, b)
1,395✔
660
    elseif b > 1
562,115✔
661
        ndigits0zpb(x, b)
13,723,342✔
662
    else
663
        throw(DomainError(b, "The base must not be in `[-1, 0, 1]`."))
129✔
664
    end
665
end
666

667
# Extends the definition in base/int.jl
668
top_set_bit(x::Integer) = ceil(Integer, log2(x + oneunit(x)))
111✔
669

670
"""
671
    ndigits(n::Integer; base::Integer=10, pad::Integer=1)
672

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

677
See also [`digits`](@ref), [`count_ones`](@ref).
678

679
# Examples
680
```jldoctest
681
julia> ndigits(0)
682
1
683

684
julia> ndigits(12345)
685
5
686

687
julia> ndigits(1022, base=16)
688
3
689

690
julia> string(1022, base=16)
691
"3fe"
692

693
julia> ndigits(123, pad=5)
694
5
695

696
julia> ndigits(-123)
697
3
698
```
699
"""
700
ndigits(x::Integer; base::Integer=10, pad::Integer=1) = max(pad, ndigits0z(x, base))
27,274,767✔
701

702
## integer to string functions ##
703

704
function bin(x::Unsigned, pad::Int, neg::Bool)
130✔
705
    m = top_set_bit(x)
130✔
706
    n = neg + max(pad, m)
130✔
707
    a = StringVector(n)
130✔
708
    # for i in 0x0:UInt(n-1) # automatic vectorization produces redundant codes
709
    #     @inbounds a[n - i] = 0x30 + (((x >> i) % UInt8)::UInt8 & 0x1)
710
    # end
711
    i = n
×
712
    @inbounds while i >= 4
1,497✔
713
        b = UInt32((x % UInt8)::UInt8)
1,367✔
714
        d = 0x30303030 + ((b * 0x08040201) >> 0x3) & 0x01010101
1,367✔
715
        a[i-3] = (d >> 0x00) % UInt8
1,367✔
716
        a[i-2] = (d >> 0x08) % UInt8
1,367✔
717
        a[i-1] = (d >> 0x10) % UInt8
1,367✔
718
        a[i]   = (d >> 0x18) % UInt8
1,367✔
719
        x >>= 0x4
1,367✔
720
        i -= 4
1,367✔
721
    end
1,367✔
722
    while i > neg
286✔
723
        @inbounds a[i] = 0x30 + ((x % UInt8)::UInt8 & 0x1)
156✔
724
        x >>= 0x1
156✔
725
        i -= 1
156✔
726
    end
156✔
727
    if neg; @inbounds a[1]=0x2d; end
164✔
728
    String(a)
130✔
729
end
730

731
function oct(x::Unsigned, pad::Int, neg::Bool)
212,596✔
732
    m = div(top_set_bit(x) + 2, 3)
212,596✔
733
    n = neg + max(pad, m)
212,596✔
734
    a = StringVector(n)
212,596✔
735
    i = n
×
736
    while i > neg
1,798,946✔
737
        @inbounds a[i] = 0x30 + ((x % UInt8)::UInt8 & 0x7)
1,586,350✔
738
        x >>= 0x3
1,586,350✔
739
        i -= 1
1,586,350✔
740
    end
1,586,350✔
741
    if neg; @inbounds a[1]=0x2d; end
212,629✔
742
    String(a)
212,596✔
743
end
744

745
# 2-digit decimal characters ("00":"99")
746
const _dec_d100 = UInt16[(0x30 + i % 10) << 0x8 + (0x30 + i ÷ 10) for i = 0:99]
747

748
function dec(x::Unsigned, pad::Int, neg::Bool)
13,156,437✔
749
    n = neg + ndigits(x, pad=pad)
13,149,117✔
750
    a = StringVector(n)
13,187,082✔
751
    i = n
×
752
    @inbounds while i >= 2
49,861,216✔
753
        d, r = divrem(x, 0x64)
36,945,196✔
754
        d100 = _dec_d100[(r % Int)::Int + 1]
37,038,234✔
755
        a[i-1] = d100 % UInt8
37,083,549✔
756
        a[i] = (d100 >> 0x8) % UInt8
37,072,571✔
757
        x = oftype(x, d)
×
758
        i -= 2
37,090,280✔
759
    end
37,066,129✔
760
    if i > neg
13,176,346✔
761
        @inbounds a[i] = 0x30 + (rem(x, 0xa) % UInt8)::UInt8
5,987,664✔
762
    end
763
    if neg; @inbounds a[1]=0x2d; end
13,178,210✔
764
    String(a)
13,171,451✔
765
end
766

767
function hex(x::Unsigned, pad::Int, neg::Bool)
18,139✔
768
    m = 2 * sizeof(x) - (leading_zeros(x) >> 2)
18,139✔
769
    n = neg + max(pad, m)
18,139✔
770
    a = StringVector(n)
18,139✔
771
    i = n
×
772
    while i >= 2
144,531✔
773
        b = (x % UInt8)::UInt8
124,141✔
774
        d1, d2 = b >> 0x4, b & 0xf
126,392✔
775
        @inbounds a[i-1] = d1 + ifelse(d1 > 0x9, 0x57, 0x30)
126,392✔
776
        @inbounds a[i]   = d2 + ifelse(d2 > 0x9, 0x57, 0x30)
126,392✔
777
        x >>= 0x8
126,392✔
778
        i -= 2
126,392✔
779
    end
126,392✔
780
    if i > neg
18,139✔
781
        d = (x % UInt8)::UInt8 & 0xf
3,817✔
782
        @inbounds a[i] = d + ifelse(d > 0x9, 0x57, 0x30)
3,817✔
783
    end
784
    if neg; @inbounds a[1]=0x2d; end
18,170✔
785
    String(a)
18,139✔
786
end
787

788
const base36digits = UInt8['0':'9';'a':'z']
789
const base62digits = UInt8['0':'9';'A':'Z';'a':'z']
790

791
function _base(base::Integer, x::Integer, pad::Int, neg::Bool)
5,891✔
792
    (x >= 0) | (base < 0) || throw(DomainError(x, "For negative `x`, `base` must be negative."))
5,891✔
793
    2 <= abs(base) <= 62 || throw(DomainError(base, "base must satisfy 2 ≤ abs(base) ≤ 62"))
5,892✔
794
    b = (base % Int)::Int
×
795
    digits = abs(b) <= 36 ? base36digits : base62digits
5,890✔
796
    n = neg + ndigits(x, base=b, pad=pad)
11,630✔
797
    a = StringVector(n)
5,890✔
798
    i = n
×
799
    @inbounds while i > neg
71,733✔
800
        if b > 0
65,843✔
801
            a[i] = digits[1 + (rem(x, b) % Int)::Int]
76,592✔
802
            x = div(x,b)
76,592✔
803
        else
804
            a[i] = digits[1 + (mod(x, -b) % Int)::Int]
1,500✔
805
            x = cld(x,b)
750✔
806
        end
807
        i -= 1
65,843✔
808
    end
65,843✔
809
    if neg; @inbounds a[1]=0x2d; end
7,295✔
810
    String(a)
5,890✔
811
end
812

813
split_sign(n::Integer) = unsigned(abs(n)), n < 0
13,195,072✔
814
split_sign(n::Unsigned) = n, false
5✔
815

816
"""
817
    string(n::Integer; base::Integer = 10, pad::Integer = 1)
818

819
Convert an integer `n` to a string in the given `base`,
820
optionally specifying a number of digits to pad to.
821

822
See also [`digits`](@ref), [`bitstring`](@ref), [`count_zeros`](@ref).
823

824
# Examples
825
```jldoctest
826
julia> string(5, base = 13, pad = 4)
827
"0005"
828

829
julia> string(-13, base = 5, pad = 4)
830
"-0023"
831
```
832
"""
833
function string(n::Integer; base::Integer = 10, pad::Integer = 1)
26,643,480✔
834
    pad = (min(max(pad, typemin(Int)), typemax(Int)) % Int)::Int
13,333,213✔
835
    if base == 2
13,382,075✔
836
        (n_positive, neg) = split_sign(n)
68✔
837
        bin(n_positive, pad, neg)
130✔
838
    elseif base == 8
13,368,974✔
839
        (n_positive, neg) = split_sign(n)
73,987✔
840
        oct(n_positive, pad, neg)
212,596✔
841
    elseif base == 10
13,158,412✔
842
        (n_positive, neg) = split_sign(n)
13,107,668✔
843
        dec(n_positive, pad, neg)
13,161,796✔
844
    elseif base == 16
24,030✔
845
        (n_positive, neg) = split_sign(n)
5,717✔
846
        hex(n_positive, pad, neg)
18,139✔
847
    else
848
        _base(base, base > 0 ? unsigned(abs(n)) : convert(Signed, n), pad, (base>0) & (n<0))
5,891✔
849
    end
850
end
851

852
string(b::Bool) = b ? "true" : "false"
1,096✔
853

854
"""
855
    bitstring(n)
856

857
A string giving the literal bit representation of a primitive type.
858

859
See also [`count_ones`](@ref), [`count_zeros`](@ref), [`digits`](@ref).
860

861
# Examples
862
```jldoctest
863
julia> bitstring(Int32(4))
864
"00000000000000000000000000000100"
865

866
julia> bitstring(2.2)
867
"0100000000000001100110011001100110011001100110011001100110011010"
868
```
869
"""
870
function bitstring(x::T) where {T}
7,705✔
871
    isprimitivetype(T) || throw(ArgumentError("$T not a primitive type"))
7,705✔
872
    sz = sizeof(T) * 8
7,705✔
873
    str = StringVector(sz)
7,705✔
874
    i = sz
7,705✔
875
    @inbounds while i >= 4
7,705✔
876
        b = UInt32(sizeof(T) == 1 ? bitcast(UInt8, x) : trunc_int(UInt8, x))
98,288✔
877
        d = 0x30303030 + ((b * 0x08040201) >> 0x3) & 0x01010101
98,288✔
878
        str[i-3] = (d >> 0x00) % UInt8
98,288✔
879
        str[i-2] = (d >> 0x08) % UInt8
98,288✔
880
        str[i-1] = (d >> 0x10) % UInt8
98,288✔
881
        str[i]   = (d >> 0x18) % UInt8
98,288✔
882
        x = lshr_int(x, 4)
98,288✔
883
        i -= 4
98,288✔
884
    end
98,288✔
885
    return String(str)
7,705✔
886
end
887

888
"""
889
    digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1)
890

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

895
See also [`ndigits`](@ref), [`digits!`](@ref),
896
and for base 2 also [`bitstring`](@ref), [`count_ones`](@ref).
897

898
# Examples
899
```jldoctest
900
julia> digits(10)
901
2-element Vector{Int64}:
902
 0
903
 1
904

905
julia> digits(10, base = 2)
906
4-element Vector{Int64}:
907
 0
908
 1
909
 0
910
 1
911

912
julia> digits(-256, base = 10, pad = 5)
913
5-element Vector{Int64}:
914
 -6
915
 -5
916
 -2
917
  0
918
  0
919

920
julia> n = rand(-999:999);
921

922
julia> n == evalpoly(13, digits(n, base = 13))
923
true
924
```
925
"""
926
digits(n::Integer; base::Integer = 10, pad::Integer = 1) =
454✔
927
    digits(typeof(base), n, base = base, pad = pad)
928

929
function digits(T::Type{<:Integer}, n::Integer; base::Integer = 10, pad::Integer = 1)
553✔
930
    digits!(zeros(T, ndigits(n, base=base, pad=pad)), n, base=base)
278✔
931
end
932

933
"""
934
    hastypemax(T::Type) -> Bool
935

936
Return `true` if and only if the extrema `typemax(T)` and `typemin(T)` are defined.
937
"""
938
hastypemax(::Base.BitIntegerType) = true
112,322✔
939
hastypemax(::Type{Bool}) = true
×
940
hastypemax(::Type{T}) where {T} = applicable(typemax, T) && applicable(typemin, T)
×
941

942
"""
943
    digits!(array, n::Integer; base::Integer = 10)
944

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

949
# Examples
950
```jldoctest
951
julia> digits!([2, 2, 2, 2], 10, base = 2)
952
4-element Vector{Int64}:
953
 0
954
 1
955
 0
956
 1
957

958
julia> digits!([2, 2, 2, 2, 2, 2], 10, base = 2)
959
6-element Vector{Int64}:
960
 0
961
 1
962
 0
963
 1
964
 0
965
 0
966
```
967
"""
968
function digits!(a::AbstractVector{T}, n::Integer; base::Integer = 10) where T<:Integer
414✔
969
    2 <= abs(base) || throw(DomainError(base, "base must be ≥ 2 or ≤ -2"))
207✔
970
    hastypemax(T) && abs(base) - 1 > typemax(T) &&
207✔
971
        throw(ArgumentError("type $T too small for base $base"))
972
    isempty(a) && return a
207✔
973

974
    if base > 0
195✔
975
        if ispow2(base) && n >= 0 && n isa Base.BitInteger && base <= typemax(Int)
163✔
976
            base = Int(base)
46✔
977
            k = trailing_zeros(base)
46✔
978
            c = base - 1
46✔
979
            for i in eachindex(a)
92✔
980
                a[i] = (n >> (k * (i - firstindex(a)))) & c
1,216✔
981
            end
2,386✔
982
        else
983
            for i in eachindex(a)
234✔
984
                n, d = divrem(n, base)
4,018✔
985
                a[i] = d
4,119✔
986
            end
4,653✔
987
        end
988
    else
989
        # manually peel one loop iteration for type stability
990
        n, d = fldmod(n, -base)
32✔
991
        a[firstindex(a)] = d
34✔
992
        n = -signed(n)
32✔
993
        for i in firstindex(a)+1:lastindex(a)
60✔
994
            n, d = fldmod(n, -base)
261✔
995
            a[i] = d
268✔
996
            n = -n
261✔
997
        end
261✔
998
    end
999
    return a
195✔
1000
end
1001

1002
"""
1003
    isqrt(n::Integer)
1004

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

1007
```jldoctest
1008
julia> isqrt(5)
1009
2
1010
```
1011
"""
1012
isqrt(x::Integer) = oftype(x, trunc(sqrt(x)))
14✔
1013

1014
function isqrt(x::Union{Int64,UInt64,Int128,UInt128})
2,012✔
1015
    x==0 && return x
2,012✔
1016
    s = oftype(x, trunc(sqrt(x)))
3,013✔
1017
    # fix with a Newton iteration, since conversion to float discards
1018
    # too many bits.
1019
    s = (s + div(x,s)) >> 1
2,011✔
1020
    s*s > x ? s-1 : s
2,011✔
1021
end
1022

1023
"""
1024
    factorial(n::Integer)
1025

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

1030
See also [`binomial`](@ref).
1031

1032
# Examples
1033
```jldoctest
1034
julia> factorial(6)
1035
720
1036

1037
julia> factorial(21)
1038
ERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` instead
1039
Stacktrace:
1040
[...]
1041

1042
julia> factorial(big(21))
1043
51090942171709440000
1044
```
1045

1046
# External links
1047
* [Factorial](https://en.wikipedia.org/wiki/Factorial) on Wikipedia.
1048
"""
1049
function factorial(n::Integer)
×
1050
    n < 0 && throw(DomainError(n, "`n` must be nonnegative."))
×
1051
    f::typeof(n*n) = 1
×
1052
    for i::typeof(n*n) = 2:n
×
1053
        f *= i
×
1054
    end
×
1055
    return f
×
1056
end
1057

1058
"""
1059
    binomial(n::Integer, k::Integer)
1060

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

1064
If ``n`` is non-negative, then it is the number of ways to choose `k` out of `n` items:
1065
```math
1066
\\binom{n}{k} = \\frac{n!}{k! (n-k)!}
1067
```
1068
where ``n!`` is the [`factorial`](@ref) function.
1069

1070
If ``n`` is negative, then it is defined in terms of the identity
1071
```math
1072
\\binom{n}{k} = (-1)^k \\binom{k-n-1}{k}
1073
```
1074

1075
See also [`factorial`](@ref).
1076

1077
# Examples
1078
```jldoctest
1079
julia> binomial(5, 3)
1080
10
1081

1082
julia> factorial(5) ÷ (factorial(5-3) * factorial(3))
1083
10
1084

1085
julia> binomial(-5, 3)
1086
-35
1087
```
1088

1089
# External links
1090
* [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.
1091
"""
1092
Base.@assume_effects :terminates_locally function binomial(n::T, k::T) where T<:Integer
12,081✔
1093
    n0, k0 = n, k
12,081✔
1094
    k < 0 && return zero(T)
12,081✔
1095
    sgn = one(T)
11,917✔
1096
    if n < 0
11,917✔
1097
        n = -n + k - one(T)
3,928✔
1098
        if isodd(k)
3,928✔
1099
            sgn = -sgn
1,964✔
1100
        end
1101
    end
1102
    k > n && return zero(T)
11,917✔
1103
    (k == 0 || k == n) && return sgn
11,752✔
1104
    k == 1 && return sgn*n
11,479✔
1105
    if k > (n>>1)
7,552✔
1106
        k = (n - k)
3,768✔
1107
    end
1108
    x = nn = n - k + one(T)
7,552✔
1109
    nn += one(T)
7,552✔
1110
    rr = T(2)
7,552✔
1111
    while rr <= k
13,141✔
1112
        xt = div(widemul(x, nn), rr)
5,589✔
1113
        x = xt % T
5,589✔
1114
        x == xt || throw(OverflowError(LazyString("binomial(", n0, ", ", k0, ") overflows")))
5,589✔
1115
        rr += one(T)
5,589✔
1116
        nn += one(T)
5,589✔
1117
    end
5,589✔
1118
    copysign(x, sgn)
7,552✔
1119
end
1120

1121
"""
1122
    binomial(x::Number, k::Integer)
1123

1124
The generalized binomial coefficient, defined for `k ≥ 0` by
1125
the polynomial
1126
```math
1127
\\frac{1}{k!} \\prod_{j=0}^{k-1} (x - j)
1128
```
1129
When `k < 0` it returns zero.
1130

1131
For the case of integer `x`, this is equivalent to the ordinary
1132
integer binomial coefficient
1133
```math
1134
\\binom{n}{k} = \\frac{n!}{k! (n-k)!}
1135
```
1136

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

1142
# External links
1143
* [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.
1144
"""
1145
function binomial(x::Number, k::Integer)
7✔
1146
    k < 0 && return zero(x)/one(k)
7✔
1147
    # we don't use prod(i -> (x-i+1), 1:k) / factorial(k),
1148
    # and instead divide each term by i, to avoid spurious overflow.
1149
    return prod(i -> (x-(i-1))/i, OneTo(k), init=oneunit(x)/one(k))
81✔
1150
end
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

© 2025 Coveralls, Inc