Search code examples
algorithmpseudocodecs50mit-scratch

How to check whether a number is prime or not (Algorithm using brute force)


I have designed an algorithm which takes an input and checks whether a number is prime or not. Is this correct?

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

Solution

  • Yes you are correct:

    Here is a better worded psedo-code:

    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