An equilateral triangle

The shape of a network is a big equilateral triangle as shown in the following picture and it consists of many small equilateral triangles of different sizes. Each point represents a computer and you have to choose a rectangle such that each of its corners is a computer and the horizontal edges are parallel with the lower edge of the network(big triangle) The size of the network is the number of small triangles on each edge of the big triangle. You need to count the number of rectangles that can be selected from the network.

Network with the size 5 and two rectangles are shown with green and red

Example:

Input:  n = 5
Output: 11

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int equalateralTriangle1(int n)
{
    int ans = 0;
    for (int i = n - 2i >= 1i--)
    {
        if (i & 1)
        {
            int m = (n - i) / 2;
            int j = i * (i + 1) / 2;
            ans += j * m;
        }
        else
        {
            int m = (n - i - 1) / 2;
            int j = i * (i + 1) / 2;
            ans += j * m;
        }
    }
    return ans;
}
int equalateralTriangle(int n)
{
    int ans = 0;
    for (int i = n - 2i >= 1i--)
    {
        if (i & 1)
        {
            int m = (n - i - 1) / 2;
            int j = i * (i + 1) / 2;
            ans += j * m;
        }
        else
        {
            int m = (n - i) / 2;
            int j = i * (i + 1) / 2;
            ans += j * m;
        }
    }
    return ans;
}
int main()
{
    int n = 5;
    if (n & 1)
        cout << equalateralTriangle1(n<< "\n";
    else
        cout << equalateralTriangle(n<< "\n";
    return 0;
}


No comments:

Post a Comment