Skip to content

Commit

Permalink
Optimize example pidigits.jl
Browse files Browse the repository at this point in the history
  • Loading branch information
BenLauwens committed Jan 7, 2021
1 parent eeb3b28 commit 2736e52
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions examples/pidigits.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,39 @@ using ResumableFunctions

using Base.GMP.MPZ: add_ui!, mul_ui!, add!, tdiv_q!
const mpz_t = Ref{BigInt}
addmul_ui!(x::BigInt,a::BigInt,b::Int64) = ccall((:__gmpz_addmul_ui,"libgmp"), Cvoid, (mpz_t,mpz_t,Culong), x, a, b)
addmul_ui!(x::BigInt,a::BigInt,b::UInt64) = ccall((:__gmpz_addmul_ui,"libgmp"), Cvoid, (mpz_t,mpz_t,Culong), x, a, b)
submul_ui!(x::BigInt,a::BigInt,b::UInt64) = ccall((:__gmpz_submul_ui,"libgmp"), Cvoid, (mpz_t,mpz_t,Culong), x, a, b)
get_ui(x::BigInt) = ccall((:__gmpz_get_ui,"libgmp"), Culong, (mpz_t,), x)

@resumable function pidigits()
k = 1
d = UInt64(0)
k = one(UInt64)
d = zero(UInt64)
numer = BigInt(1)
denom = BigInt(1)
accum = BigInt(0)
tmp1 = BigInt(0)
tmp2 = BigInt(0)
tmp3 = BigInt(0)
while true
k2 = 2k + 1
addmul_ui!(accum, numer, 2)
k2 = 2k + one(UInt64)
addmul_ui!(accum, numer, UInt64(2))
mul_ui!(accum, k2)
mul_ui!(denom, k2)
mul_ui!(numer, k)
k += 1
k += one(UInt64)
if numer <= accum
mul_ui!(tmp1, numer, 3)
mul_ui!(tmp1, numer, UInt64(3))
add!(tmp1, accum)
tdiv_q!(tmp2, tmp1, denom)
d = get_ui(tmp2)
mul_ui!(tmp1, numer, 4)
mul_ui!(tmp1, numer, UInt64(4))
add!(tmp1, accum)
tdiv_q!(tmp2, tmp1, denom)
if d == get_ui(tmp2)
tdiv_q!(tmp3, tmp1, denom)
if tmp2 == tmp3
d = get_ui(tmp2)
@yield d
submul_ui!(accum, denom, d)
mul_ui!(accum, 10)
mul_ui!(numer, 10)
mul_ui!(accum, UInt64(10))
mul_ui!(numer, UInt64(10))
end
end
end
Expand All @@ -63,4 +64,5 @@ function main(n = parse(Int64, ARGS[1]))
end
end


main(100)

0 comments on commit 2736e52

Please sign in to comment.