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.