Skip to content

Commit

Permalink
add BigInt prevpow2/nextpow2 (fix JuliaLang#4814)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevengj committed Nov 15, 2013
1 parent 8039fa7 commit e85e0a0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import Base: *, +, -, /, <, <<, >>, >>>, <=, ==, >, >=, ^, (~), (&), (|), ($),
binomial, cmp, convert, div, divrem, factorial, fld, gcd, gcdx, lcm, mod,
ndigits, promote_rule, rem, show, isqrt, string, isprime, powermod,
widemul, sum, trailing_zeros, trailing_ones, count_ones, base, parseint,
serialize, deserialize, bin, oct, dec, hex, isequal, invmod
serialize, deserialize, bin, oct, dec, hex, isequal, invmod,
prevpow2, nextpow2

type BigInt <: Integer
alloc::Cint
Expand Down Expand Up @@ -414,4 +415,7 @@ widemul(x::Int128, y::Uint128) = BigInt(x)*BigInt(y)
widemul(x::Uint128, y::Int128) = BigInt(x)*BigInt(y)
widemul{T<:Integer}(x::T, y::T) = BigInt(x)*BigInt(y)

prevpow2(x::BigInt) = x < 0 ? -prevpow2(-x) : (x <= 2 ? x : one(BigInt) << (ndigits(x, 2)-1))
nextpow2(x::BigInt) = x < 0 ? -nextpow2(-x) : (x <= 2 ? x : one(BigInt) << ndigits(x-1, 2))

end # module
12 changes: 12 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1551,3 +1551,15 @@ end
# negative power domain error
@test_throws powermod(1,-2,1)
@test_throws powermod(big(1),-2,1)

# prevpow2/nextpow2:
@test nextpow2(0) == prevpow2(0) == 0
for i = -2:2
@test nextpow2(i) == prevpow2(i) == i
end
@test nextpow2(56789) == -nextpow2(-56789) == 65536
@test prevpow2(56789) == -prevpow2(-56789) == 32768
for i = -100:100
@test nextpow2(i) == nextpow2(big(i))
@test prevpow2(i) == prevpow2(big(i))
end

0 comments on commit e85e0a0

Please sign in to comment.