求解模方程的 C/C++ 程式?
我們有 n 枚硬幣,我們要用這些硬幣搭建一個最大高度的金字塔。我們將把第一枚硬幣放在第一行,第二枚和第三枚硬幣放在第二行,以此類推
在下圖中,我們用 6 枚硬幣搭了一個高度為 3 的金字塔。我們無法搭建高度為 4 的金字塔,但我們需要 10 枚硬幣。用以下公式很容易得出高度:
H = {(-1+ √(1+8N))/2}
Input: n = 10 Output: Height of pyramid: 4
說明
使用此公式計算高度
H = {(-1+ √(1+8N))/2}
示例
#include <iostream> #include <math.h> using namespace std; int main() { int n=10; int height = (-1 + sqrt(1 + 8 * n)) / 2; cout << "Height of pyramid: " <<height; }
廣告