TCS CodeVita Coding Questions

TCS CodeVita Coding Questions with Solutions

TCS CodeVita Season 11 is the eleventh edition of the prestigious coding competition TCS CodeVita which is organized by TCS every year, in the search of world’s  best coder. TCS CodeVita is a global level coding competition, in which participants from all over the world compete for the title of “World’s Best Coder” and a prize money of 20,000 US$. On this page, TCS CodeVita Coding Questions are given which help you to prepare for TCS CodeVita.

Go through TCS CodeVita Coding Questions page to practice Coding Questions for TCS CodeVita.

TCS CodeVita Coding Questions

TCS CodeVita Coding Questions with Solutions

Civil War

Problem Description
In this superhero epic, the denizens of the Marvel Universe are forced to pick sides when Captain America and Iron Man come to blows over ideological differences.
The government decides to push for the Hero Registration Act, a law that limits a hero’s actions. This results in a division in The Avengers. Iron Man stands with this Act, claiming that their actions must be kept in check otherwise cities will continue to be destroyed, but Captain America feels that saving the world is daring enough and that they cannot rely on the government to protect the world. And here the civil war begins.

They are trying make their team stronger by adding more avengers to their team. There are N avengers lined up.

Rules to add avenger to their team-

  • Any team can start first. But they will alternatively only.
  • They can select avenger from any side. But if they start from one side they can’t move to other side in current chance.
  • They can select consecutive avengers as many they want.
  • They will stop only when all the avengers are part of either side.
  • Every Avenger has a power associated with him
  • There are some spurious avengers who will decrease the overall power of the team.

Both teams will select players optimally. Find the difference of powers of the two teams

Constraints
1<= N <= 10^6
-10^9 <= p[i] <= 10^9

Input
First line contains an integer denoting the number of Avengers(N).
Next lines contain N space separated values denoting power of every avenger(P[i]).

Output
Print the difference of the powers of teams
– Time Limit (secs)
1

Examples :
Input
5
2-78-1 20

Output
2

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Use Coupon Code “CT10” and get a flat 10% OFF on your Prime plus one month extension on 12 months and above plans.

Encryption

Problem Description
John is working in high security organization, where he needs to deal with lot of confidential documents. He must encrypt the important number in documents. Please help John to write a program where the system should identify the integer number and encrypt number based on John’s actions.

John’s actions are as follows

ActionsDenoted byRemarks
Right arrowRMove to next character
Left arrowTMove to previous character
Up arrowLIncrement the integer by one
Down arrowDDecrement the integer by one
SwapSnSwap the current position with number in the nth position

These actions are governed by the rules mentioned below.

Rules

  • Initial position is at the first character of the string comprised of numbers.
  • When incrementing the value of a number at a current location, if the number is 9 then it remains 9 else it increases by 1.
  • When decrementing the value of a number at a current location, if the number is 0 then it remains O else it decreases by 1.
  • Once all the actions from the action string are consumed, if any part of the input string remained unprocessed then leave those characters of the input string as they are.

Constraints
0 <n<= I where I is length of the input string.

Input
First line contains a string comprising of numbers. This is referred to as input string in the rest of the document.
Second line contains the actions denoted by values mentioned in the table above. This is referred to as action string in the rest of the document.

Output
Single string comprising of numbers.

Time Limit (secs)
1

Examples

Input
123456
RLTDRRTRS2S1

Output
244156

Explanation

Initial string: 123456

Action: RLTDRRTRS2S1

R: 1[2]3456
L: [1]23456
T: [2]23456
D: [1]23456
R: 1[2]3456
R: 12[3]456
T:12[4]456
R: 124[4]56
S2: 144[2]56
S1: 244[1]56

output string.

Since all the actions from the action string are consumed and only first four characters of the input string are processed leave the last two as they are and make them the part of

Possible Legal Subsets

Problem Description

You are given N comma-separated Strings. You need to form all possible legal subsets of these N strings. These subsets will be a combination of zero or more of these N Strings After forming the subsets, they will be ranked in a particular onder. The legal subset formation and ranking logic is as described below

  • Rank 1 will always be an empty set
  • Next N ranks will be the N Strings that appear in the order they are provided in the input
  • After N + 1 ranks, you need to combine N strings such that all legal combinations are formed
  • Legal combination simply means that while combinations are formed, the string that appears to the left of a particular string in the input, can never appear to the right of that particular string, when subsets are formed
  • A subset with less elements will be ranked higher than a subset with more elements (NOTE-Rank 1 is higher than rank 2)
  • Refer Example 2 to get a better understanding of how subsets are formed and ranked
  • It is guaranteed that
  • N>=1
  • All N strings are unique

Example: you are having an input string “aa,cc,bb” in this string we can see we have three strings which are comma separated. Now from this group of string we have to create all possible subset of strings. 8 subsets can be formed from these strings. And they are as follows:

  1. {}
  2. {aa}
  3. {cc}
  4. {bb}
  5. {aa,}

Note: here we can see the ranks given to the subsets are first by size i.e., the subset with lesser number of strings is ranked higher than the subset with higher size. If the subsets have equal number of strings then, the combination which is formed earlier (by virtue of combining strings in order they appear in input), gets a higher rank.

For example, rank of su bset (aa,cc) > rank of (aa,bb) because string cc is appearing prior to string bb in the input. Similarly, rank of (cc) > rank of (bb).

You are provided one rank R and for that you have to print the Rth subset from all legal subsets.

Constraints:

0<N<=10^2

0<R<=10^18

Input

First line contains an integer N which is number of strings in group.

Second line contains an integer R, for which you have to find Rth subset from all legal subsets.

Third line contains N comma-separated strings basis which the subsets should be formed

Output:

From all possible legal subsets find the subset whose rank is R

Time Limit (secs)
1

Input

2

4

a,b

Output

a,b

Explanation:

Given that N = 2, given

Second line: Rank to be find: 4th

Third line: Given group of strings: a,b

Possible subsets & Rank

{}-1

{a} -2

{b}-3

{a, b}-4

Output – a,b (4th rank corresponds to a,b)

Use Coupon Code “CT10” and get a flat 10% OFF on your Prime plus one month extension on 12 months and above plans.

Seating Arrangement

Problem Description

You are a caretaker of a waiting room and you have to take care of empty seats such that all the people should sit together. Imagine the seats are in a straight line like in a movie theatre. People are seated on random seats initially. Your task is to make them sit together so that minimum number of people change their position. Also, they can be made to sit together in many ways. Find the number of ways you can make them sit together by requiring only minimal people movement.

“E” depicts an empty seat and “O” depicts an occupied seat. Input will be given in the form of a string.

Example: OEOEO

As we can see, only seat number 1, 3, 5 are occupied and 2 and 4 are empty.

Case 1: If we move 5th person to 2nd position, they can all be together with only one person moving his/her place.

Case 2: If we movement 1st person to 4th position, they can all be together with only one person moving his/her place.

They can all be together with only one movement and this can be done in 2 ways. Print the minimum number of movements required and the number of ways this minimum movement can help achieve the objective.

Note: If they are already sitting together, Print “00” as output.

Constraints
0 <N <= 100000

Input

First line contains an integer N which depicts the number of seats

Second line contains N characters each of which are either “O” or “E”. “O” denotes an occupied seat and “E” denotes an empty seat.

Output
Print minimum number of movements required and the number of ways in which all people can be made to sit together without exceeding minimum number of movements by space
Time Limit (secs)
1

Examples
Input
5

OEOEO

Output
1 2

Explanation:

Given data of 5 seats in the queue,

Seat number 2 and 4 are unoccupied and all the other seats are occupied.

We can make them sit together by moving only one person near to the other. It can be done in 2 ways:

OOOEE (Moving 4 person to 2º position)

 

EE000 (Moving 1 person to 4 position)

Polygon with Maximum Area

Problem Description:

You are given N number of coordinates and you have to create a polygon from these points such that they will make a polygon with maximum area.

Note: coordinates provided in the input may or may not be in sequential form.

Constraints
1 <= N <= 10

Input:

First line contains an integer N which depicts number of co-ordinates

Next N lines consist of two space separated integer depicting coordinates of in form of xy

Output:
Print the maximum possible area possible by creating a polygon by joining the coordinates. 

If the area is in decimal form, print the absolute value as output.

Time Limit (secs):
1

Examples:
Input:

4

0  0

2  0

0  2

2  2

Output:

4

Explanation:

As we can imagine that these points will make a square shape and the maximum possible area made by the polygon will be 4.

Bank Compare Problem

Problem Description

Question – : There are two banks – Bank A and Bank B. Their interest rates vary. You have received offers from both banks in terms of the annual rate of interest, tenure, and variations of the rate of interest over the entire tenure.You have to choose the offer which costs you least interest and reject the other. Do the computation and make a wise choice.

The loan repayment happens at a monthly frequency and Equated Monthly Installment (EMI) is calculated using the formula given below :

EMI = loanAmount * monthlyInterestRate / ( 1 – 1 / (1 + monthlyInterestRate)^(numberOfYears * 12))

Constraints:

  • 1 <= P <= 1000000
  • 1 <=T <= 50
  • 1<= N1 <= 30
  • 1<= N2 <= 30

Input Format:

  • First line: P principal (Loan Amount)
  • Second line: T Total Tenure (in years).
  • Third Line: N1 is the number of slabs of interest rates for a given period by Bank A. First slab starts from the first year and the second slab starts from the end of the first slab and so on.
  • Next N1 line will contain the interest rate and their period.
  • After N1 lines we will receive N2 viz. the number of slabs offered by the second bank.
  • Next N2 lines are the number of slabs of interest rates for a given period by Bank B. The first slab starts from the first year and the second slab starts from the end of the first slab and so on.
  • The period and rate will be delimited by single white space.

Output Format: Your decision either Bank A or Bank B.

Explanation:

  • Example 1
    • Input
    • 10000
    • 20
    • 3
    • 5 9.5
    • 10 9.6
    • 5 8.5
    • 3
    • 10 6.9
    • 5 8.5
    • 5 7.9
  • Output: Bank B
  • Example 2
    • Input
    • 500000
    • 26
    • 3
    • 13  9.5
    • 3  6.9
    • 10  5.6
    • 3
    • 14  8.5
    • 6  7.4
    • 6  9.6
  • Output: Bank A

 

Consecutive Prime Sum

Problem Description

Question – :  Some prime numbers can be expressed as a sum of other consecutive prime numbers.

  • For example
    • 5 = 2 + 3,
    • 17 = 2 + 3 + 5 + 7,
    • 41 = 2 + 3 + 5 + 7 + 11 + 13.
      Your task is to find out how many prime numbers which satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2.

Write code to find out the number of prime numbers that satisfy the above-mentioned property in a given range.

Input Format: First line contains a number N

Output Format: Print the total number of all such prime numbers which are less than or equal to N.

Constraints: 2<N<=12,000,000,000

Counting Rock Sample

Problem Description

Question – : Juan Marquinho is a geologist and he needs to count rock samples in order to send it to a chemical laboratory. He has a problem: The laboratory only accepts rock samples by a range of its size in ppm (parts per million).

Juan Marquinho receives the rock samples one by one and he classifies the rock samples according to the range of the laboratory. This process is very hard because the number of rock samples may be in millions.

Juan Marquinho needs your help, your task is to develop a program to get the number of rocks in each of the ranges accepted by the laboratory.

Input Format: An positive integer S (the number of rock samples) separated by a blank space, and a positive integer R (the number of ranges of the laboratory); A list of the sizes of S samples (in ppm), as positive integers separated by space R lines where the ith line containing two positive integers, space separated, indicating the minimum size and maximum size respectively of the ith range.

Output Format: R lines where the ith line contains a single non-negative integer indicating the number of the samples which lie in the ith range.

Constraints:

  • 10 <= S <= 10000
  • 1 <= R <= 1000000
  • 1<=size of Sample <= 1000

Example 1

  • Input: 10 2
  • 345 604 321 433 704 470 808 718 517 811
  • 300 350
  • 400 700

Output: 2 4

Explanation:

There are 10 samples (S) and 2 ranges ( R ). The samples are 345, 604,811. The ranges are 300-350 and 400-700. There are 2 samples in the first range (345 and 321) and 4 samples in the second range (604, 433, 470, 517). Hence the two lines of the output are 2 and 4

Example 2

  • Input: 20 3
  • 921 107 270 631 926 543 589 520 595 93 873 424 759 537 458 614 725 842 575 195
  • 1 100
  • 50 600
  • 1 1000

Output: 1 12 20

Explanation:

There are 20 samples and 3 ranges. The samples are 921, 107 195. The ranges are 1-100, 50-600 and 1-1000. Note that the ranges are overlapping. The number of samples in each of the three ranges are 1, 12 and 20 respectively. Hence the three lines of the output are 1, 12 and 20.

kth Largest factor of N

Problem Description

Question -: A positive integer d is said to be a factor of another positive integer N if when N is divided by d, the remainder obtained is zero. For example, for number 12, there are 6 factors 1, 2, 3, 4, 6, 12. Every positive integer k has at least two factors, 1 and the number k itself.Given two positive integers N and k, write a program to print the kth largest factor of N.

Input Format: The input is a comma-separated list of positive integer pairs (N, k).

Output Format: The kth highest factor of N. If N does not have k factors, the output should be 1.

Constraints:

  • 1<N<10000000000
  • 1<k<600.

You can assume that N will have no prime factors which are larger than 13.

Example 1

  • Input: 12,3
  • Output: 4

Explanation: N is 12, k is 3. The factors of 12 are (1,2,3,4,6,12). The highest factor is 12 and the third largest factor is 4. The output must be 4.

Example 2

  • Input: 30,9
  • Output: 1

Explanation: N is 30, k is 9. The factors of 30 are (1,2,3,5,6,10,15,30). There are only 8 factors. As k is more than the number of factors, the output is 1.

Collecting Candies

Problem Description

Question:- Krishna loves candies a lot, so whenever he gets them, he stores them so that he can eat them later whenever he wants to.

He has recently received N boxes of candies each containing Ci candies where Ci represents the total number of candies in the ith box. Krishna wants to store them in a single box. The only constraint is that he can choose any two boxes and store their joint contents in an empty box only. Assume that there are an infinite number of empty boxes available.

At a time he can pick up any two boxes for transferring and if both the boxes contain X and Y number of candies respectively, then it takes him exactly X+Y seconds of time. As he is too eager to collect all of them he has approached you to tell him the minimum time in which all the candies can be collected.

Input Format:

  • The first line of input is the number of test case T
  • Each test case is comprised of two inputs
  • The first input of a test case is the number of boxes N
  • The second input is N integers delimited by whitespace denoting the number of candies in each box

Output Format: Print minimum time required, in seconds, for each of the test cases. Print each output on a new line.

Constraints:

  • 1 < T < 10
  • 1 < N< 10000
  • 1 < [Candies in each box] < 100009
S. No.InputOutput
11
4
1 2 3 4
19
21
5
1 2 3 4
34

Explanation for sample input-output 1:

4 boxes, each containing 1, 2, 3 and 4 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Hence total time taken is 19 seconds. There could be other combinations also, but overall time does not go below 19 seconds.

Explanation for sample input-output 2:

5 boxes, each containing 1, 2, 3, 4 and 5 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Adding 5 + 10 in a new box takes 15 seconds.Hence total time taken is 34 seconds. There could be other combinations also, but overall time does not go below 33 seconds.

Staircase Problem

Problem Description

There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time.

  • Count the number of ways, the person can reach the top.

Maneuvering a Cave Problem

Problem Description

The task is to count all the possible paths from top left to bottom right of a m x n matrix with the constraints that from each cell you can either move only to right or down.

Input: 

  • First line consists of T test cases. First line of every test case consists of N and M, denoting the number of rows and number of columns respectively.

Output: 

  • Single line output i.e count of all the possible paths from top left to bottom right of a m x n matrix..

Constraints:

  • 1<=T<=100
  • 1<=N<=100
  • 1<=M<=100

Houses Problem

Problem Description

Question:- There are n houses build in a line, each of which contains some value in it.

 A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbours left and right side.

What is the maximum stolen value?

Sample Input: val[] = {6, 7, 1, 3, 8, 2, 5}

Sample Output: 20

Square Free Numbers Problem

Problem Description

In the theory of numbers, square free numbers have a special place.  A square free number is one that is not divisible by a perfect square (other than 1).  Thus 72 is divisible by 36 (a perfect square), and is not a square free number, but 70 has factors 1, 2, 5, 7, 10, 14, 35 and 70.  As none of these are perfect squares (other than 1), 70 is a square free number.

For some algorithms, it is important to find out the square free numbers that divide a number.  Note that 1 is not considered a square free number. 

In this problem, you are asked to write a program to find the number of square free numbers that divide a given number.

Input:-

  • The only line of the input is a single integer N which is divisible by no prime number larger than 19.

Output:-

  • One line containing an integer that gives the number of square free numbers (not including 1).

Constraints:-

  • N   < 10^9

Complexity:-

  • Simple

Time Limit:-

  • 1

Examples


Example 1

  • Input:-
    20
  • Output:-
    3

Explanation

N=20

If we list the numbers that divide 20, they are

1, 2, 4, 5, 10, 20

1 is not a square free number, 4 is a perfect square, and 20 is divisible by 4, a perfect square.  2 and 5, being prime, are square free, and 10 is divisible by 1,2,5 and 10, none of which are perfect squares.  Hence the square free numbers that divide 20 are 2, 5, 10.  Hence the result is 3.

Example 2

  • Input:-
    72
  • Output:-
    3

Explanation

N=72.  The numbers that divide 72 are

1, 2, 3, 4, 6, 8, 9, 12, 18, 24, 36, 72

1 is not considered square free.   4, 9 and 36 are perfect squares, and 8,12,18,24 and 72 are divisible by one of the.  Hence only 2, 3 and 6 are square free.  (It is easily seen that none of them are divisible by a perfect square).  The result is 3.

Coin Distribution Problem

Problem Statement

Find the minimum number of coins required to form any value between 1 to N,both inclusive.Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.Let’s Understand the problem using the following example. Consider the value of N is 13, then the minimum number of coins required to formulate any value between 1 and 13, is 6. One 5 Rupee, three 2 Rupee and two 1 Rupee coins are required to realize any value between 1 and 13. Hence this is the answer.However, if one takes two 5 Rupee coins, one 2 rupee coin and two 1 rupee coin, then too all values between 1 and 13 are achieved. But since the cumulative value of all coins equals 14, i.e., exceeds 13, this is not the answer.

  • Input Format:
    • A single integer value.
  • Output Format:
    • Four space separated integer values.
      • 1st – Total number of coins.
      • 2nd – number of 5 Rupee coins.
      • 3rd – number of 2 Rupee coins.
      • 4th – number of 1 Rupee coins.
  • Constraints:
    • 0 < n < 1000

Refer the sample output for formatting

Sample Input

    13

Sample Output

   6 1 3 2

Explanation

  • The minimum number of coins required is 6 with in it:
    • minimum number of 5 Rupee coins = 1
    • minimum number of 2 Rupee coins = 3
    • minimum number of 1 Rupee coins = 2

Using these coins, we can form any value with in the given value and itself, like below:

Here the given value is 13

  • For 1 = one 1 Rupee coin
  • For 2 = one 2 Rupee coin
  • For 3 = one 1 Rupee coin and one 2 Rupee coins
  • For 4 = two 2 Rupee coins
  • For 5 = one 5 Rupee coin
  • For 6 = one 5 Rupee and one 1 Rupee coins
  • For 7 = one 5 Rupee and one 2 Rupee coins
  • For 8 = one 5 Rupee, one 2 Rupee and one 1 Rupee coins
  • For 9 = one 5 Rupee and two 2 Rupee coins
  • For 10 = one 5 Rupee, two 2 Rupee and one 1 Rupee coins
  • For 11 = one 5 Rupee, two 2 Rupee and two 1 Rupee coins
  • For 12 = one 5 Rupee, three 2 Rupee and one 1 Rupee coins
  • For 13 = one 5 Rupee, three 2 Rupee and two 1 Rupee coins

Total Distance Covered by the Beetle

Problem Description

A 10cm x 10cm x 10cm solid cube rests on the ground. It has a beetle on it, as well as some sweet honey spots on the cube’s surface. The beetle begins at a point on the cube’s surface and moves in a clockwise direction along the cube’s surface to the honey spots.

  • If it goes from one point on the same face to another (say, X to Y), it goes in an arc of a circle that subtends an angle of 60 degrees at the circle’s center.
  • If it travels from one point to another on a different face, it takes the shortest path on the cube’s surface, except that it never travels along its bottom.

The beetle is a Cartesian geometry student who knows the coordinates (x, y, z) of all the points it needs to visit. Its coordinate origin is one of the cube’s corners on the ground, and the z-axis points up. As a result, z=0 is the bottom surface (on which it does not crawl), and z=10 is the top. The beetle keeps track of all distances traveled and rounded the distance to two decimal places when it arrives at the following location so that the final distance is a sum of the rounded distances from spot to spot.

Input

The first line returns an integer N, the total number of points visited by the beetle (including the starting point).

The second line contains 3N non-negative numbers, each with two decimal places. These are to be interpreted as the x, y, and z coordinates of the points the beetle must visit in the given order.

Output

One line containing a number representing the total distance traveled by the beetle to two decimal places. Even if the travel distance is an integer, the output should have two decimal places.

Constraints

None of the points visited by the beetle are on the bottom face (z=0) or on any of the cube’s edges (the lines where two faces meet)

2<=N<=10

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

25 comments on “TCS CodeVita Coding Questions”


  • Madhan Kumar

    PrimeConstructionMarks: 30
    Problem Description
    A math game is introduced in a school competition to test the skills of students. The game deals with Prime numbers.

    The game rules are as follows:

    From the given set of distinct natural numbers as input, consider the smallest natural number as q.
    Your task is to compute the smallest prime number (p) such that when p is divided by all the distinct numbers in the input, except q, should result q as the remainder.
    Constraints
    1 < n < 11

    p < 10 ^ 10

    Input
    Input consists of n+1 number of distinct natural numbers separated by spaces.

    Output
    Print single integer p if such a p exists, else print "None".

    Time Limit (secs)
    1

    Examples
    Input

    3 4 5 1

    Output

    61

    Explanation

    Here the n+1 numbers are 3, 4, 5 and 1 where q=1 (the least of the numbers)

    The smallest number that leaves remainder 1 when divided by 3, 4 and 5 is 61 and is prime. Hence, output is 61.

    Example 2

    Input

    3 4 5 2

    Output

    None

    Explanation

    Here q=2. Any number that when divided by 4 leaving remainder 2 must be an even number e.g., 6, 10, 14 etc. Hence it can't be prime. Hence, output is "None" please post the code for above problem


  • AKASH

    Moving average
    Class arrangement
    Snake and ladder
    Graph
    Number encryption
    Card game
    Please post the codes for the above programs.


  • omprakash

    For square free number, the solution given here is not the time efficient answer. It gives time out exception error since the max size input in 10^9.


    • omprakash

      **************SQUARE FREE NUMBERS***************

      #include
      #include
      int main(){
      int n;
      int ar[]={2,3,5,7,11,13,17,19};
      scanf(“%d”,&n);
      int c=0;
      for(int i=0;i<8;i++){
      if(n%ar[i]==0)
      c++;
      }
      int res = pow(2,c)-1;
      printf("%d\n",res);
      return 0;
      }


  • Saket

    Java Solution for Stair Case Problem
    public class StairCaseProblem {
    static int Stair(int n) {
    if(n<=0)
    return 0;
    if(n==1) {
    return 1;
    }
    else if(n==2) {
    return 2;
    }
    else {
    return Stair(n-1)+Stair(n-2);
    }
    }
    public static void main(String[] args) {
    int n = 15;
    System.out.println(Stair(n));
    }
    }


  • Saket

    Java solution for Square Free Number Problem

    public class SquareFreeNumbersProblem {

    static boolean isPrime(int a) {
    boolean b = true;
    for(int i = 2 ; i<=a/2 ; i++) {
    if(a%i==0) {
    b = false;
    }
    }
    return b;
    }

    static boolean perfectSquare(int a) {
    double d1 = Math.sqrt(a);
    int q1 = (int)d1;
    if(q1==d1) {
    return true;
    }
    else
    return false;
    }

    static boolean isSquarefree(int a) {
    boolean b = true;
    if(perfectSquare(a)) {
    return false;
    }else {
    for(int i = 2 ; i < a ; i++) {
    if(a%i == 0) {
    double d = Math.sqrt(i);
    int q = (int)d;
    if(q == d) {
    b = false;
    break;
    }
    }
    }
    }
    return b;
    }

    public static void main(String[] args) {
    int n = 70;
    int count = 0;
    for(int i = 2 ; i<=n/2 ; i++) {
    if(n%i == 0) {

    if(isPrime(i) ) {
    count++;

    }
    else if(isSquarefree(i)) {
    count++;

    }
    }
    }
    System.out.println(count);
    }
    }


  • Saket

    Solution for Consecutive Prime Sum mentioned below your code is not give right output in java

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public class ConsecutivePrimeSum {
    public static void main(String[] args) {
    int n = 1045;
    List l = new ArrayList();
    l.add(2);
    int count = 0;
    for(int i = 3 ; i<n;i++) {
    boolean b= true;
    for(int j = 2 ; j<=i/2 ; j++) {
    if(i%j == 0) {
    b = false;
    break;
    }
    }
    if(b) {
    l.add(i);
    Collections.sort(l);
    int sum = 0;
    int j = 0;
    while(sum<=i) {
    sum += l.get(j++);
    if(sum == i) {
    count++;
    //System.out.println(i);
    break;
    }
    }
    }
    }
    System.out.println(count);
    }
    }


  • AKASH

    CORRECT SOLUTION FOR CONSECUTIVE PRIME SUM
    #include

    int isprime(int n){
    for(int i=2;i<=n/2;i++)
    {
    if(n%i==0)
    return 0;
    }
    return 1;
    }

    int main(){
    int n,sum=0;
    int arr[25],count=0;
    scanf("%d",&n);
    for(int i=2;i=5 && sum<=n){
    if(isprime(sum))
    count++;
    }
    }
    }
    printf("%d ",count);
    }


    • AKASH

      #include

      int isprime(int n){
      for(int i=2;i<=n/2;i++)
      {
      if(n%i==0)
      return 0;
      }
      return 1;
      }

      int main(){
      int n,sum=0;
      int arr[25],count=0;
      scanf("%d",&n);
      for(int i=2;i=5 && sum<=n){
      if(isprime(sum))
      count++;
      }
      }
      }
      printf("%d ",count);
      }


  • srija

    can you provide solution to codevita Digitpairs problem and Deathbattle problem.


      • Srichandra

        Death Battle
        Problem Description
        In a crossover fantasy universe, Houin Kyoma is up in a battle against a powerful monster Nomu that can kill him in a single blow. However being a brilliant scientist Kyoma found a way to pause time for exactly M seconds. Each second, Kyoma attacks Nomu with certain power, which will reduce his health points by that exact power. Initially Nomu has H Health Points. Nomu dies when his Health Points reach 0. Normally Kyoma performs Normal Attack with power A. Besides from Kyoma’s brilliance, luck plays a major role in events of this universe. Kyoma’s Luck L is defined as probability of performing a super attack. A super attack increases power of Normal Attack by C. Given this information calculate and print the probability that Kyoma kills Nomu and survives. If Kyoma dies print “RIP”.
        Constraints
        0 < T <= 50
        1 <= A, H, C, L1, L2 <= 1000
        1 <= M <= 20.
        L1<=L2
        Input Format
        First line is integer T denoting number of test cases.
        Each test case consist of single line with space separated numbers A H L1 L2 M C. Where luck L is defined as L1/L2. Other numbers are, as described above.
        Output
        Print probability that Kyoma kills Nomu in form P1/P2 where P1<=P2 and gcd(P1,P2)=1. If impossible, print “RIP” without quotes.
        Timeout
        1
        Explanation
        Example 1
        Input
        2
        10 33 7 10 3 2
        10 999 7 10 3 2
        Output
        98/125
        RIP


        • Vaibhav Jain

          Thanks Srichandra for providing us this questions. We surely provide the answer for this question, as soon as we could

          0

      • Srichandra

        Digit Pairs
        Problem Description
        Given N three-digit numbers, your task is to find bit score of all N numbers and then print the number of pairs possible based on these calculated bit score.
        1. Rule for calculating bit score from three digit number:
        From the 3-digit number,
        • extract largest digit and multiply by 11 then
        • extract smallest digit multiply by 7 then
        • add both the result for getting bit pairs.
        Note: – Bit score should be of 2-digits, if above results in a 3-digit bit score, simply ignore most significant digit.
        Consider following examples:
        Say, number is 286
        Largest digit is 8 and smallest digit is 2
        So, 8*11+2*7 =102 so ignore most significant bit , So bit score = 02.
        Say, Number is 123
        Largest digit is 3 and smallest digit is 1
        So, 3*11+7*1=40, so bit score is 40.
        2. Rules for making pairs from above calculated bit scores
        Condition for making pairs are
        • Both bit scores should be in either odd position or even position to be eligible to form a pair.
        • Pairs can be only made if most significant digit are same and at most two pair can be made for a given significant digit.
        Constraints
        N<=500
        Input Format
        First line contains an integer N, denoting the count of numbers.
        Second line contains N 3-digit integers delimited by space
        Output
        One integer value denoting the number of bit pairs.
        Timeout
        1
        Explanation
        Example 1
        Input
        8 234 567 321 345 123 110 767 111
        Output
        3
        Explanation
        After getting the most and least significant digits of the numbers and applying the formula given in Rule 1 we get the bit scores of the numbers as:
        58 12 40 76 40 11 19 18
        No. of pair possible are 3:
        40 appears twice at odd-indices 3 and 5 respectively. Hence, this is one pair.
        12, 11, 18 are at even-indices. Hence, two pairs are possible from these three-bit scores.
        Hence total pairs possible is 3


        • Vaibhav Jain

          Thanks Srichandra for providing us this questions. We surely provide the answer for this question, as soon as we could

          0

        • Soumyadeep

          I solved this in Java.
          Can you check if i did right, sir?
          import java.io.*;
          import java.util.*;
          public class Bitpairs
          {
          public static void main(String args[])throws IOException
          {
          Scanner sc=new Scanner(System.in);
          int N=sc.nextInt();
          int arr[]=new int[N];
          int check[]=new int[N];
          int counte=0,counto=0,finals=0;
          for(int i=0;i<N;i++)
          {
          arr[i]=sc.nextInt();
          }
          for(int i=0;i<N;i++)
          {
          check[i]=bitcalc(arr[i]);
          }
          for(int i=1;i<9;i++)
          {
          for(int j=0;j=2)
          {
          finals=finals+(int)(Math.ceil(Double.valueOf(counte)/2));
          }
          counte=0;
          if(counto>=2)
          {
          finals=finals+(int)(Math.ceil(Double.valueOf(counto)/2));
          }
          counto=0;
          }
          System.out.println(finals);
          }
          static int bitcalc(int N)
          {
          int max=0,min=999;
          int temp=N;
          while(temp>0)
          {
          int d=temp%10;
          if(d>max)
          {
          max=d;
          }
          if(d0)
          {
          int d2=temp2%10;
          c++;
          temp2=temp2/10;
          }
          if(c==3)
          {
          sum=sum%100;
          }
          return sum;
          }
          }

          0

  • kajol

    In ConsecutivePrimeSum problem output is wrong.
    For n= 43,the output should be 3 not 4. Because there are only 5, 17, 41 prime numbers which satisfies the condition