C語言中直角等腰三角形內最多能容納多少個2×2的正方形
給定一個直角等腰三角形。等腰三角形是指兩條邊長度相等的三角形。直角三角形是指高(圖中的ag)和底(圖中的dg)相互垂直的三角形。目標是找到可以放入這個邊長為2個平方單位的直角等腰三角形中的最大正方形數量。底邊或高(兩者相等)作為輸入。正方形的數量作為輸出。
參考下圖瞭解問題

給定的高為ag,底為gd的三角形有3個邊長為2的正方形。從角端'a'和'd'開始,三角形aib和cde永遠不會貢獻任何正方形。所以首先我們總是需要額外2個單位長度的三角形。現在我們必須將剩餘的底gd(或高ag)除以2來計算正方形的數量。高度(ag)也是如此。
while(base > 2 ) squares+=(base-2)/2 base = base-2. Use formula of Ap = b*(b+1)/2….where new b=b-2
讓我們透過例子來理解。
輸入 - 底邊:12
輸出 - 正方形數量:15
說明
base 12>2, squares 10/2=5, new base 12-2=10 base 10>2, squares 8/2=4, new base 10-2=8 base 8>2, squares 6/2=3, new base 8-2=6 base 6>2, squares 4/2=2, new base 6-2=4 base 4>2, squares 2/2=1, new base 4-2=2 base 2>2 X Total squares=5+4+3+2+1=15
輸入 - 0.5
輸出 - 正方形數量 - 1
說明
base 5>2, squares 3/2=1, new base 5-2=3 base 3>2, squares 1/2=0, new base 3-2=1 base 1>2 X Total squares=1
下面程式中使用的演算法如下
整型變數base用於儲存三角形的底邊。
函式numofSquares(int b)用於計算底邊為b的三角形可以容納的正方形數量。
首先b=b-2 - 角端處的額外空間
根據公式,b=floor(b/2),這個新的b可以有b*(b+1)/2個邊長為2的正方形。
將計算結果作為正方形的數量返回。
示例
#include <stdio.h>
#include <math.h>
int numofSquares(int b){
// removing the extra part we would
// always need
b = (b - 2);
// Since each square has base of
// length of 2
b = floor(b / 2);
return b * (b + 1)/2;
}
int main(){
int base = 8;
printf("Maximum no. of square that can be accommodated : %d",numofSquares(base));
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Maximum no. of square that can be accommodated : 6
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP