求解 C++ 中棋盘中方格数量的程序
在此问题中,我们将获得一个棋盘的大小。我们的任务是创建一个程序来用 C++ 求出棋盘中方格的数量。
问题描述 − 求解棋盘中方格的数量。我们需要计算棋盘中所有方格的组合,即认为边长为 1x1、2x2、3x3 ... nxn 的方格。
让我们通过一个示例来理解该问题:
输入: n = 4.
输出: 30
Squares of size 1x1 -> 16 Squares of size 2x2 -> 9 Squares of size 3x3 -> 4 Squares of size 4x4 -> 1 Total number of squares = 16+9+4+1 = 30
解决方案方法
A simple approach is by using the sum formula for nxn grid. Let’s deduct the general formula for the sum, sum(1) = 1 sum(2) = 1 + 4 = 5 sum(3) = 1 + 4 + 9 = 14 sum(4) = 1 + 4 + 9 + 16 = 30 The sum is can be generalised as sum = 12 + 22 + 32 + 42 + … n2 sum = ( (n*(n+1)*((2*n) + 1))/6 )
示例
#include <iostream> using namespace std; int calcSquaresCount(int n){ int squareCount = ( (n * (n+1) * (2*n + 1))/6 ); return squareCount; } int main() { int n = 6; cout<<"The total number of squares of size "<<n<<"X"<<n<<" is "<<calcSquaresCount(n); }
输出
The total number of squares of size 6X6 is 91
广告