function fibonacci(n::Int)
n < 2 && return n
x, y, bits = big(0), big(1), []
while n > 0
pushfirst!(bits, Bool(n&0x1))
n >>= 1
end
for bit ∈ bits[1:end-1]
u, v = x * (x + 2y), (x^2 + y^2)
x, y = bit ? (u + v, u) : (u, v)
end
u = x * (x + 2y)
bits[end] ? u + x^2 + y^2 : u
end
map(x->println(x, "\t=>\t", fibonacci(x)), 0:10)
@time fib = fibonacci(100000000)
@time len = ceil(Int, log10(fib))
println(len)
function primeCount(maxn::Int)
mark_array = trues(maxn)
cnt = 1 # count for 2
for i in 3:2:maxn
if mark_array[i]
cnt += 1
j, delta = i^2, 2i
while j <= maxn
mark_array[j] = false
j += delta
end
end
end; cnt
end
@time println(primeCount(10^8))
julia> function primeCount2(maxn::Int)
mark_array = trues(maxn)
cnt = 1 # count for 2
@inbounds for i in 3:2:maxn
if mark_array[i]
cnt += 1
j, delta = i^2, 2i
while j <= maxn
mark_array[j] = false
j += delta
end
end
end; cnt
end
primeCount2 (generic function with 1 method)
运行速度最好用 BenchmarkTools 来测量
julia> using BenchmarkTools
julia> @btime primeCount(10^8)
488.427 ms (3 allocations: 11.92 MiB)
5761455
julia> @btime primeCount2(10^8)
446.679 ms (3 allocations: 11.92 MiB)
5761455
function primes(n::Int64)
nlen=ceil(n/2);
nlen=convert(Int64,nlen)
p=trues(nlen);
q = length(p);
temp=sqrt(convert(Float64,n));
ua = floor(sqrt(n));
ub=convert(Int64,ua)
for k = 3:2:ub
if p[div(k+1,2)]
for i=div(k*k+1,2):k:q
p[i] = false;
end
end
end
s=0
for px in p
if px
s += 1
end
end
return s
end
这样更快