![](/img/trans.png)
[英]If p is prime, how to check whether ap + b is prime or not using a fast algorithm?
[英]How to check whether a number is prime or not (Algorithm using brute force)
我設計了一個算法,它接受一個輸入並檢查一個數字是否是素數。 這樣對嗎?
1)Input num
2)counter= num-1
3)repeat
4)remainder = num%counter
5)if rem=0 then
6)broadcast not a prime.no and stop
7)decrement counter by 1
8)until counter = 1
9)say its a prime and stop
是的,你是對的:
這是一個措辭更好的psedo代碼:
get Num from user
get IsPrime = True
for PFactor ranges from 2 to Num-1 do
begin block
if Num divisible by PFactor then set IsPrime = False
end block
if IsPrime = True then display Num is prime
else display Num is not prime
有一種稱為埃拉托色尼篩法的算法,用於查找最多為n
素數。 漸近復雜度是O(nlog(logn)) 。
偽代碼類似於:
- 從 0..max 創建一個數組
- 從 2 開始,從數組中刪除每個 2 的倍數。
- 然后,回到開頭,刪除每一個 3 的倍數。
- 從數組開頭的下一個可用數字開始重復此操作。
- 這樣做直到您檢查的數字的平方大於您的最大數字。
- 最后,壓縮原始數組。
然后,該數組將僅包含最大數量的素數。 你會發現它真的非常有效。 如此高效,您可以將其用作輔助方法來確定一個數是否為素數。 想知道數字 105557 是素數嗎? 只需要 66 步。
紅寶石代碼:
def sieve(max)
# Set up an array with all the numbers from 0 to the max
primes = (0..max).to_a
# Set both the first and second positions (i.e., 0 and 1) to nil, as they
# aren't prime.
primes[0] = primes[1] = nil
# Iterate through primes array
counter = 0
primes.each do |p|
# Skip if nil
next unless p
# Break if we are past the square root of the max value
break if p*p > max
counter += 1
# Start at the square of the current number, and step through.
# Go up to the max value, by multiples of the current number, and replace
# that value with nil in the primes array
(p*p).step(max,p) { |m| primes[m] = nil }
end
# Finally, return the compacted array.
puts "Solved for #{max} in #{counter} steps."
primes.compact
end
要檢查一個數是否為素數:
def prime?(num)
sieve(num).include?(num)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.