簡體   English   中英

如何檢查一個數是否為素數(使用蠻力的算法)

[英]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))

偽代碼類似於:

  1. 從 0..max 創建一個數組
  2. 從 2 開始,從數組中刪除每個 2 的倍數。
  3. 然后,回到開頭,刪除每一個 3 的倍數。
  4. 從數組開頭的下一個可用數字開始重復此操作。
  5. 這樣做直到您檢查的數字的平方大於您的最大數字。
  6. 最后,壓縮原始數組。

然后,該數組將僅包含最大數量的素數。 你會發現它真的非常有效。 如此高效,您可以將其用作輔助方法來確定一個數是否為素數。 想知道數字 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM