Algorithm
Problem link- https://www.spoj.com/problems/TRICOUNT/
TRICOUNT - Counting Triangles
We define the LEVEL of a triangle as in the following illustrative image:
Task: Your task is very easy. All you have to do is to count all triangles in the biggest one (Level N).
Input
The first line of the input contains an integer T (T ≤ 10000) - the number of test cases and T lines follow. Each line contains an integer N (1 ≤ N ≤ 106) which is the level of the triangle in that test case.
Output
For each test case, you should write a seperate line: the number of triangles in the biggest one (Level N). (All answers will fit within the range of a 64-bit integer)
Example
Input:
3
1
2
3
Output:
1
5
13
Source limit is 500 bytes.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int n;
long long s, s2;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
cin>>s;
s2 = (s * (s + 2) * (2 * s + 1) / 8);
cout<<s2<<endl;;
}
}
Copy The Code &
Try With Live Editor
Input
1
2
3
Output
5
13
#2 Code Example with Java Programming
Code -
Java Programming
# include <stdio.h>
# define ll long long
int main()
{
ll T,n,result;
scanf("%lld",&T);
while(T--)
{
scanf("%lld",&n);
if(n%2==0)
{
result=((n*(n+2))*(2*n+1))/8;
printf("%lld\n",result);
}
else
{
result=(((n*(n+2))*(2*n+1))-1)/8;
printf("%lld\n",result);
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
1
2
3
Output
5
13
Demonstration
SPOJ Solution-TRICOUNT Counting Triangles-Solution in C, C++, Java, Python,TRICOUNT,SPOJ Solution