Robotic moves | Hackerearth practice problem solution

Problem:-

A robot's initial position is $\left(0,0\right)$ and it can only move along X-axis. It has $N$ moves to make and in each move, it will select one of the following options:

1. Go to $\left(X-1,0\right)$ from $\left(X,0\right)$
2. Go to $\left(X+1,0\right)$ from $\left(X,0\right)$
3. Remain at its current position

Your task is to calculate $\sum \left(abs\left(X\right)+abs\left(Y\right)\right)$ for all reachable $\left(X,Y\right)$.

Note: Here, $abs$ denotes the absolute value.

See the sample explanation for better understanding.

Input format

• The first line contains $T$ denoting the number of test cases.
• The first line of each test case containing an integer $N$ denoting the number of moves.

Output format

Print $T$ lines. For each test case, print a single integer as described in the problem statement.

Constraints

$1\le T\le 20000$

$1\le N\le 1e9$

Sample Input
1
1
Sample Output
2
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

He is initially at (0,0). He has 1 move to make, the positions where he can end up are (-1,0),(1,0) and (0,0).

$\sum \left(abs\left(x\right)+abs\left(y\right)\right)$

=abs(-1)+abs(0)+abs(1)+abs(0)+abs(0)+abs(0)

=1+0+1+0+0+0

=2

Code:-

Here I am going to give you two solution first one is on the basis of C language and second one is on the basis of c++ language which you can submit in c++14 and c++17 also

Solution 1 ( C language):-

#include<stdio.h>
int main()
{
long long t, a, sum=0, i, j;
scanf("%lld",&t);
for(i=0; i<t; i++)
{
scanf("%lld",&a);
printf("%lld\n",a*(a+1));
}
}

Solution 2 ( C++ language):-

This solution is based on the c++ language and you can submit ib c++14 and c++17 also.

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

int main()
{
int t;
long long int n;
cin>>t;
while(t--)
{
cin>>n;
cout<<n*(n+1)<<endl;

}
return 0;
}

Recommended Post:-

• Hackerearth Problems:-

Data structure:-
Key points:-