给出一个N*N的正方形方格,问能找到多少个正方形?矩形呢(不包括正方形)?
题目扩展到了3维和4维,三维的如下图,对应的是正方体和立方体(不包括正方体)
用ans1[k]表示k维下的正方形个数,ans2[k]表示k维下矩形个数,推下公式:
先考虑二维的情况,然后推广。
边长为 i 的二维正方形个数:[a_2[i]=(N-i+1)^2]
总的正方形个数:
[ecause sum_{i=1}^{N}(N-i+1)^2=sum_{i=1}^{N}i^2]
[ herefore sum_{i=1}^{N}a[i]=sum_{i=1}^{N}i^2=frac{N(N+1)(2N+1)}{6}]
长i宽j的矩形(包括正方形)个数:
[c_2[i,j]=(N-i+1)^2(N-j+1)^2]
总的矩形个数(包括正方形):
[sum_{i=1}^{N}sum_{j=1}^{N}c[i,j]=sum_{i=1}^{N}sum_{j=1}^{N}(i imes j)=[frac{N(N+1)}{2}]^2]
推广到k维。
边长为i的k维正方形个数:
[a_k[i]=(N-i+1)^k]
总的k维正方形个数:
[sum_{i+1}^{N}a_k[i]=sum_{i+1}^{N}i^k]
k维矩形(第j个边长分别为(i_j)包括k维正方形)个数:
[c_k[i]=prod_{j=1}^{k}(N-i_j+1),i_j=1,2,cdots,N]
k维矩形(包括k维正方形)总数:
[sum_{j=1}^{N}sum_{i_j=1}^{N}c_k[i]=sum_{j=1}^{N}sum_{i_j=1}^{N}prod_{j=1}^{k}i_j]
[ecause sum_{i=1}^{N}sum_{j=1}^{M}(i imes j)=1 imessum_{j=1}^{M}+2 imessum_{j=1}^{M}+cdots+N imessum_{j=1}^{M}=(sum_{i=1}^{N}i) imes(sum_{j=1}^{M}j)]
[ herefore sum_{j=1}^{N}sum_{i_j=1}^{N}prod_{j=1}^{k}i_j=prod_{j=1}^{k}(sum_{i_j=1}^{N}i_j)=prod_{j=1}^{k}frac{N(N+1)}{2}=[frac{N(N+1)}{2}]^k]
[ herefore sum_{j=1}^{N}sum_{i_j=1}^{N}c_k[i]=[frac{N(N+1)}{2}]^k]
结果:
[ ext{ans1[k]}=sum_{i=1}^{N}i^k]
[ ext{ans2[k]}=[frac{N(N+1)}{2}]^k- ext{ans1[k]}]
复杂度O(n)。
1A
# include <stdio.h> int main() { int n; while (scanf("%d", &n) != EOF) { long long ans1[3], ans2[3]; ans1[0] = ans1[1] = ans1[2] = 0; for (int i = 1; i <= n; ++i) { ans1[0] += i*i; ans1[1] += i*i*i; ans1[2] += i*i*i*i; } long long int t = n*(n+1)/2; ans2[0] = t*t-ans1[0]; ans2[1] = t*t*t-ans1[1]; ans2[2] = t*t*t*t-ans1[2]; printf("%lld %lld %lld %lld %lld %lld ", ans1[0], ans2[0], ans1[1], ans2[1], ans1[2], ans2[2]); } return 0; }