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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP