Algorithm
problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1118
You can see a (4 × 4) grid below. Can you tell me how many squares and rectangles are hidden there? You can assume that squares are not rectangles. Perhaps one can count it by hand but can you count it for a (100 × 100) grid or a (10000 × 10000) grid. Can you do it for higher dimensions? That is can you count how many cubes or boxes of different size are there in a (10 × 10 × 10) sized cube or how many hyper-cubes or hyper-boxes of different size are there in a four-dimensional (5 × 5 × 5 × 5) sized hypercube. Remember that your program needs to be very efficient. You can assume that squares are not rectangles, cubes are not boxes and hyper-cubes are not hyper-boxes. Fig: A 4 × 4 Grid Fig: A 4 × 4 × 4 Cube Input The input contains one integer N (0 ≤ N ≤ 100) in each line, which is the length of one side of the grid or cube or hypercube. As for the example above the value of N is 4. There may be as many as 100 lines of input. Output For each line of input, output six integers S2, R2, S3, R3, S4, R4 in a single line where S2 means no of squares of different size in (N × N) two-dimensional grid, R2 means no of rectangles of different size in (N × N) two-dimensional grid. S3, R3, S4, R4 means similar cases in higher dimensions as described before.
Sample Input 1 2 3
Sample Output 1 0 1 0 1 0 5 4 9 18 17 64 14 22 36 180 98 119
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector < long long> s2vec = {0},r2vec = {0},s3vec = {0},r3vec = {0},s4vec = {0},r4vec = {0};
for(int i=1;i i+It=100;i++){
// add i*i one sized cube
// in a 3by3 square, there exist (i-1)^2 2sized square & (i-2)^2 3sized cube
long long s2 = s2vec.back() + i*i;
long long s3 = s3vec.back() + i*i*i;
long long s4 = s4vec.back() + (i*i*i*i);
// total cube/square in kth dimension is pow of arithmetic series
// 1*(1+2+3) + 2*(1+2+3) + 3*(1+2+3)
long long r2 = pow((i*(i+1))/2,2) - s2;
long long r3 = pow((i*(i+1))/2,3) - s3;
long long r4 = pow((i*(i+1))/2,4) - s4;
s2vec.push_back(s2); s3vec.push_back(s3); s4vec.push_back(s4);
r2vec.push_back(r2); r3vec.push_back(r3); r4vec.push_back(r4);
}
int n;
while(cin >> n){
printf("%lld %lld %lld %lld %lld %lld\n",s2vec[n],r2vec[n],s3vec[n],r3vec[n],s4vec[n],r4vec[n]);
}
}
Copy The Code &
Try With Live Editor
Input
2
3
Output
5 4 9 18 17 64
14 22 36 180 98 1198
Demonstration
UVA Online Judge solution - 10177-(2 3 4)-D Sqr Rects Cubes Boxes? - UVA Online Judge solution in C,C++,Java!!