【问题标题】:Modify a given pseudocode such that it contains no loops修改给定的伪代码,使其不包含循环
【发布时间】:2020-08-18 18:36:35
【问题描述】:

考虑伪代码:

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'
}

我必须修改这个伪代码,使其中没有循环,所以我必须摆脱顶部的那个 while 循环。我查看了一些示例,即数字{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} 和代码导致显示N 的数字{2, 3, 5, 6, 7, 8}{1, 4, 9, 100} 它显示D 后跟它们各自的平方根(分别为{1, 2, 3, 10})。

所以我得出结论,只有当n 是一个完美的平方时,代码才会输出D,然后它显示它的平方根。对于不是完全平方的数字,它会输出N

这意味着我必须更改上面的伪代码,以便它检查数字n 是否是一个完美的正方形。但是我怎么能在不使用任何循环的情况下做到这一点呢?特别是因为这是伪代码,所以我没有像sqrt(n) 这样的函数。我从一个通常有简单问题的来源得到这个练习,所以它一定是一些我看不到的简单的东西,没有什么复杂的。但是我看不到任何使用给定变量的方法,或者创建新变量来检查给定数字n 是否是没有任何循环的完美正方形。

【问题讨论】:

  • 我不同意您在伪代码中没有sqrt(n)。我实际上会声称你有任何你想要的操作。所以你的分析很有意义,我认为预期的解决方案确实只是取平方根并检查它是否为整数。但当然很难确定提问者的意图是什么。
  • 你可以通过调用函数或使用for循环来检查一个数字是否是sqrt......你不能同时忽略这两者......
  • 问题相当于用未指定的语言编写一些代码。如果没有关于语言是什么以及什么是循环的详细信息,就无法真正回答。也许if exists(x natural number) such that x*x == n then write 'D', x else write 'N'。或者使用递归,或者使用内置整数平方根...

标签: algorithm pseudocode perfect-square


【解决方案1】:

一种方法是将while expression 替换为recursive function

举个例子

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

写于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")
  }
}

输出

D 8
N

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2022-12-11
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多