以三角形排列硬幣時獲得最大高度的 Python 程式


在本文中,我們將瞭解如何解決以下問題陳述。

問題陳述 − 給定 N 枚硬幣,我們需要將其排列成三角形的形式,即第一行有 1 枚硬幣,第二行有 2 枚硬幣,依此類推,我們需要顯示 N 枚硬幣可以達到的最大高度。

現在讓我們觀察以下實現中的解決方案 −

示例

 動態演示

# squareroot
def squareRoot(n):
   # initial approximation
   x = n
   y = 1
   e = 0.000001 # allowed error
   while (x - y > e):
      x = (x + y) / 2
      y = n/x
   return x
# max height
def find(N):
   # calculating portion of the square root
   n = 1 + 8*N
   maxH = (-1 + squareRoot(n)) / 2
   return int(maxH)
# main
N = 17
print("Maximum height is :",find(N))

輸出

Maximum height is : 5

所有變數均在區域性作用域中宣告,並且在上圖中可以看到它們的引用。

結論

在本文中,我們學習瞭如何製作以三角形排列硬幣時獲得最大高度的 Python 程式。

更新於: 20-Dec-2019

172 次瀏覽

開啟您的事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.