gpt4 book ai didi

julia - 在 Julia 中使用 for 循环打印范围内的素数

转载 作者:行者123 更新时间:2023-12-05 09:07:33 26 4
gpt4 key购买 nike

我正在学习 Julia 语法,而且我对一般编码不熟悉。我正在寻找一种使用 for 循环和 if 语句打印给定范围内所有素数的方法。(像这样)。

for num in 1:100
if num > 1
for i in 1:(num)
if (num % i) == 0
print(num)
end
end
end
end

最佳答案

如果您有兴趣,这里有一个基于 Sieve of Eratosthenes 的替代解决方案:

UPPERLIMIT = 100

#=
Create an array of booleans called "is_prime" which is initially true
for all odd numbers, false for all even numbers
=#
is_prime = [(i % 2) > 0 for i in 1:UPPERLIMIT]
is_prime[2] = true # 2 is the exception, an even prime

#=
Now iterate through the array up to the square root of UPPERLIMIT.
factors which are bigger than sqrt(UPPERLIMIT) must have co-factors
that are smaller, so there's no need to search above that limit.
=#
for num in 3:2:floor(Int,sqrt(UPPERLIMIT))
#=
Every time we find a prime, wipe out all of its multiples.
We can start at 3*num since 2*num is already masked out
because it's even. Adding odd multiples would also yield
even outcomes, so they can be stepped over as well.
=#
if is_prime[num]
for i in 3*num:2*num:UPPERLIMIT
is_prime[i] = false
end
end
end

# Everything that hasn't been masked out to false is now prime!
for i in 2:UPPERLIMIT
if is_prime[i]
println(i)
end
end

请注意,这与蛮力方法的实际代码行数(去除注释后)几乎相同。两者产生相同的结果,但这个版本要快得多 - 在我的笔记本电脑上生成 664579 个素数到 10_000_000 需要 2.1 秒对 67 秒。


附录

我自己是 Julia 的新手,并且在玩这个的过程中一直在学习。这导致了下面的版本,我用 &&foreach 替换了条件循环。我删除了注释以强调需要的代码有多么少:

UPPERLIMIT = 100

is_prime = [(i % 2) > 0 for i in 1:UPPERLIMIT]
is_prime[2] = true # 2 is the exception, an even prime

for num in 3:2:floor(Int,sqrt(UPPERLIMIT))
is_prime[num] && foreach(i -> is_prime[i] = false, num*num:2*num:UPPERLIMIT)
end

foreach(i -> is_prime[i] && println(i), 2:UPPERLIMIT)

这个变体不仅涉及更少的代码,而且运行速度更快——1.41 秒对比 2.1 秒生成高达 10M 的素数。

关于julia - 在 Julia 中使用 for 循环打印范围内的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64730891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com