我正在使用 Julia 语言,并注意到我编写的小程序非常慢。怀疑它与for循环有某种关系,我将其重写为使用while,并且速度提高了大约 15 倍。
我确信我在范围等方面做错了什么,但我不知道是什么。
function primes_for()
num_primes = 0
for a = 2:3000000
prime = true
sa = floor(sqrt(a))
for c in 2:sa
if a % c == 0
prime = false
break
end
end
if prime
num_primes += 1
end
end
println("Number of primes is $num_primes")
end
function primes()
num_primes = 0
a = 2
while a < 3000000
prime = true
c = 2
while c * c <= a
if a …Run Code Online (Sandbox Code Playgroud) julia ×1