Search This Blog

Sunday, April 27, 2014

Algorithms - Discrete Mathematics - Diwali Lights

Diwali Lights

The following is the solution to Hacker Rank problem Diwali Lights using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

The Approach I'm following is given below:
  1. The problem is easy, if we have 2 bulbs atleast 1 bulb should be set at any time so there are 22-1 possibilities eliminating the condition where all the bulbs are turned off.
  2. So if we have N bulbs then we have 2N-1 possibilities which is large  number to compute.
  3. We can do this easily with Java's BigInteger , we can calculate the power using pow function.
  4. Also we must note since this number is large we are asked to print the result mod 105 we can also do this easily with Java's BigInteger mod function.
Score: 5/5
/**
 *
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;

/**
 * @author Arun.G
 *
 */
public class Solution {

       /**
        * @param args
        */
       static BufferedReader in = new BufferedReader(new InputStreamReader(
                     System.in));

       public static BigInteger ExponentBySquare(long x, long n)
    {
              BigInteger big = BigInteger.valueOf(x)
                   .pow((int)n)
                   .subtract(BigInteger.ONE).mod(new BigInteger("100000"));
             
              return big;
    }
       public static void main(String[] args) throws NumberFormatException,
                     Exception {
             
              int T = Integer.parseInt(in.readLine());
       
        for(int i=0;i<T;i++)
          {
          long noOfBulbs = Long.parseLong(in.readLine());
          System.out.println(ExponentBySquare(2,noOfBulbs).toString());
        }
       
        in.close();
             
             

       }
}


Your Comments are Welcome !

No comments:

Post a Comment

Labels