循环打印出一个号码,如果isPrime
是真的,但isPrime
被设置为false
当您检查值4
,并且从来都没有再次设置为true。
你的程序包含一个你想检查的每个数字的外循环和一个检查该数字的内循环。
这个内部循环的设计使得素数不会触及isPrime
,对于复合数字它会将isPrime
设置为false。因此对于素数,isPrime
的值将是内循环开始前的值。由于您希望isPrime
在质数结束时为true
,因此您应该在内循环之前将isPrime
设置为true。
一旦你这样做了,你的程序仍然有一个bug。您的算法在sqrt(n)
重要的地方有点困惑。
其他一些建议:
习惯使用局部变量而不是全局变量。这将有助于避免在意外重置您不想要的变量的情况下出现的错误。
local isPrime = true
使用一致的缩进。当任何人读取你的代码时它会有所帮助。在这种情况下,您的if isPrime == true then print(i) end
代码不会缩进。
您可以在if
条件下跳过== true
条件:if isPrime then print(i) end
。
有寻找所有的素数高达名为Sieve of Eratosthenes一定值更好的算法。下面是在Lua的实现:
function sieve_of_eratosthenes(n)
local is_prime = {}
for i = 1, n do
is_prime[i] = 1 ~= i
end
for i = 2, math.floor(math.sqrt(n)) do
if is_prime[i] then
for j = i*i, n, i do
is_prime[j] = false
end
end
end
return is_prime
end
local primes = sieve_of_eratosthenes(444)
for key, value in pairs(primes) do
if (value) then
print(key)
end
end