Tuesday, 23 September 2014

Hackerrank Utopian Tree


Problem Statement
The Utopian Tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter. 
Now, a new Utopian Tree sapling is planted at the onset of spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?

SOURCE CODE:

 #include<stdio.h>  
 void main()  
 {  
   int t,test,total;  
   scanf("%d",&test);  
   while(test--){  
     scanf("%d",&t);  
     total=1;  
     int flag=1;  
     while(t--)  
     {  
       if(flag){  
         if(total==1){  
           total+=1;  
         }else{  
         total*=2;  
         }  
       flag--;  
       }  
       else{  
         total+=1;  
         flag++;  
       }  
     }  
     printf("%d\n",total);  
   }  
 }   

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

3 comments:

  1. #include
    #include
    #include
    #include


    int main() {
    int test=0, i=0, n[100]={0}, k=0, result=0;

    scanf ("%d", &test);

    for (i=0; i<test; i++)
    {
    scanf("%d", &n[i]);

    if (n[i] == 0 )
    result = 1;
    else if (n[i] == 1)
    result = 2;
    else
    result = 2;

    for (k=2; k<=n[i]; k++)
    {
    if(k%2 == 0 )
    result += 1;
    else
    result *= 2;
    }
    printf ("%d\n", result);
    result = 0;
    }

    return 0;
    }

    ReplyDelete
  2. Which library classes are included

    ReplyDelete
    Replies
    1. stdio.h is enough to run the above program.

      functions such as printf and scanf are defined in the library "stdio.h"

      Delete