Modify a given pseudocode such that it contains no loops

123 views Asked by At

Consider the pseudocode:

read n (non-zero natural number)
x <- 1
y <- n
d <- 2
while x < y
{
    if n % d = 0
    { 
        x <- d
        y <- [n / d]

    }

    d <- d + 1

}

if x = y
{
    write 'D', x
}

else
{
    write 'N'
}

I have to modify this pseudocode such that there are no loops in it, so I have to get rid of that while loop at the top. I went through some examples, namely the numbers {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} and the code resulted in showing N for the numbers {2, 3, 5, 6, 7, 8} and for {1, 4, 9, 100} it showed D followed by their respective square roots ({1, 2, 3, 10} respectively).

So I concluded that the code outputs D only when n is a perfect square, and then it shows its square root. For the numbers that are not perfect squares, it outputs N.

That means I have to change the above pseudocode such that it checks if the number n is a perfect square or not. But how can I do that without using ANY loops? Especially since this is pseudocode, so I don't have a function like sqrt(n). I got this exercise from a source that usually has simple problems, so it must be something simple that I just don't see, nothing complicated. But I don't see any way of using the given variables, or creating new ones to check if the given number n is a perfect square without any loops.

1

There are 1 answers

0
Chema On

One approach would be replace the while expression with a recursive function.

As an example

read n (non-zero natural number)
  // recursive function loop, inside of method read
  loop(num,x,y,d)
    if x < y
      if num % d = 0
        loop(num, d, n / d, d + 1) // recursive function call      
      else 
        loop(num, x, y, d + 1)  // recursive function call      
    else  // exit of the loop function
      if x = y
        return d - 1  // it is a perfect square
      else
        return -1      // it is not a perfet square
        
  // recursive function call      
  res = loop(n,1,n,2)  
  if res = -1
    write 'N'
  else    
    write res

written in Scala

object PerfetSquare {
  def read(n: Int): Int = {
    @tailrec
    def loop(num: Int,x: Int,y: Int, d: Int): Int = {
      if(x < y) {
        if(num % d == 0) {
          loop(num, d, n / d, d + 1)
        } else {
          loop(num, x, y, d + 1)
        }
      } else if (x == y){
        d - 1  // it is a perfect square
      } else {
        -1     // it is not a perfect square
      }
    }
    loop(n,1,n,2)
  }

  def main(args: Array[String]): Unit = {
   val res = read(64)
    if(res == -1) println("N")
    else println(s"D $res")

   val res2 = read(65)
    if(res2 == -1) println("N")
    else println(s"D $res2")
  }
}

output

D 8
N