Conversion of Looping to Recursive Solution

时光怂恿深爱的人放手 提交于 2021-02-11 05:12:37

问题


I have written a method pythagoreanTriplets in scala using nested loops. As a newbie in scala, I am struggling with how can we do the same thing using recursion and use Lazy Evaluation for the returning list(List of tuples). Any help will be highly appreciated.

P.S: The following method is working perfectly fine.

// This method returns the list of all pythagorean triples whose components are
// at most a given limit. Formula a^2 + b^2 = c^2

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = {
    // triplet: a^2 + b^2 = c^2
    var (a,b,c,m) = (0,0,0,2)
    var triplets:List[(Int, Int, Int)] = List()
    while (c < limit) {
      breakable {
        for (n <- 1 until m) {
          a = m * m - n * n
          b = 2 * m * n
          c = m * m + n * n
          if (c > limit)
            break
          triplets = triplets :+ (a, b, c)
        }
        m += 1
      }
    }// end of while
    triplets
  }

回答1:


I don't see where recursion would offer significant advantages.

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = 
  for {
    m <- (2 to limit/2).toList
    n <- 1 until m
    c =  m*m + n*n if c <= limit
  } yield (m*m - n*n, 2*m*n, c)


来源:https://stackoverflow.com/questions/60469775/conversion-of-looping-to-recursive-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!