Algorithm 如何检查一个数字是否为素数(使用蛮力的算法)

Algorithm 如何检查一个数字是否为素数(使用蛮力的算法),algorithm,pseudocode,cs50,mit-scratch,Algorithm,Pseudocode,Cs50,Mit Scratch,我设计了一个算法,它接受一个输入并检查一个数字是否为素数。这是正确的吗 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 an

我设计了一个算法,它接受一个输入并检查一个数字是否为素数。这是正确的吗

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

有一种算法称为寻找素数到n个数。渐近复杂性是onlogn

伪代码类似于:

从0..max创建数组 从2开始,从数组中删除2的每一个倍数。 然后,回到开头,删除3的每一个倍数。 从阵列开头的下一个可用编号开始重复此操作。 执行此操作,直到检查的数字的平方大于最大数字。 最后,压缩原始阵列。 这个数组将只包含最大数的素数。你会发现它非常非常有效。非常有效,您可以将其用作确定数字是否为素数的辅助方法。想知道105557是素数吗?只需要66步

Ruby代码:

要检查数字是否为素数,请执行以下操作:

是的,你是对的:

下面是一个措辞更好的psedo代码:

请参阅:
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
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