C++ 中計算棋盤中奇數邊長正方形的數量


給定一個數字 size 作為 size*size 棋盤的維度作為輸入。目標是找到可以在該棋盤內形成的具有奇數長度的正方形的數量。

例如

輸入

size=3

輸出

Count of squares with odd side length in Chessboard are: 10

解釋

All squares will be as shown : and 1 whole square of size 3x3.

輸入

size=4

輸出

Count of squares with odd side length in Chessboard are: 20

解釋

there will be 16, 1X1 squares. And 4, 3X3 squares inside it.

下面程式中使用的演算法如下

在這種方法中,我們將從正方形的長度為 1 到長度為 size 進行遍歷。對於每個奇數長度,我們將 ( size−i−1)2 新增到計數中。

  • 將整數 size 作為棋盤邊的輸入。

  • 函式 square_odd_length(int size) 獲取 size 並返回棋盤中奇數邊長正方形的數量。

  • 將初始計數設定為 0。

  • 從 i=1 到 i=size 以 2 為增量遍歷,以獲取 i 的奇數值。

  • 對於每個 i,取 temp=size−i+1。

  • 將 temp*temp 新增到計數中。

  • 在 for 迴圈結束時,返回計數作為結果。

示例

 現場演示

#include <bits/stdc++.h>
using namespace std;
int square_odd_length(int size){
   int count = 0;
   for (int i = 1; i <= size; i = i + 2){
      int temp = size − i + 1;
      count = count + (temp * temp);
   }
   return count;
}
int main(){
   int size = 6;
   cout<<"Count squares with odd side length in Chessboard are: "<<square_odd_length(size);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count squares with odd side length in Chessboard are: 56

更新於: 2021年1月5日

779 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告