黒木玄
2018-01-23
using BenchmarkTools
function calc_pi_by_gcd(N)
s = 0
for a in -N÷2:N÷2-1
for b in -N÷2:N÷2-1
s += ifelse(gcd(a,b)==1, 1, 0)
end
s
end
sqrt(6N^2/s)
end
calc_pi_by_gcd(1000)
3.141073690252139
@time calc_pi_by_gcd(20000)
16.899303 seconds (84 allocations: 6.107 KiB)
3.141637566767511
function calc_pi_by_gcd_parallel(N)
c = @parallel (+) for a in -N÷2:N÷2-1
s = 0
for b in -N÷2:N÷2-1
s += ifelse(gcd(a,b)==1, 1, 0)
end
s
end
sqrt(6N^2/c)
end
calc_pi_by_gcd_parallel(1000)
3.141073690252139
@time calc_pi_by_gcd_parallel(20000)
2.816551 seconds (1.76 k allocations: 142.422 KiB)
3.141637566767511
versioninfo()
Julia Version 0.6.2 Commit d386e40c17* (2017-12-13 18:08 UTC) Platform Info: OS: Windows (x86_64-w64-mingw32) CPU: Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz WORD_SIZE: 64 BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell) LAPACK: libopenblas64_ LIBM: libopenlibm LLVM: libLLVM-3.9.1 (ORCJIT, haswell)
nprocs()
9