Header Ads Widget

Robotic moves | Hackerearth practice problem solution

   Problem:-

A robot's initial position is (0,0) 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 (X1,0) from (X,0)
  2. Go to (X+1,0) from (X,0)
  3. Remain at its current position

Your task is to calculate (abs(X)+abs(Y)) for all reachable (X,Y).

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

1T20000

1N1e9

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).

(abs(x)+abs(y))

=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:-



Post a Comment

0 Comments