Project Euler #116: Red, green or blue tiles

  • + 0 comments

    My java code passed the first case but "Termited due to Timeout" in other.

    Can Anyone help me in optimizing the code ?

    import java.io.*;
    import java.util.*;
    import java.math.*;
    
    public class Solution 
    {
        static BigInteger permutation(BigInteger n , BigInteger k)
        {
            BigInteger result = BigInteger.ONE;
            for (BigInteger bi = BigInteger.valueOf(1); bi.compareTo(k) <= 0; bi = bi.add(BigInteger.ONE)) 
            {
                result = result.multiply(n);
                result = result.divide(bi);
                n = n.subtract(BigInteger.ONE);
            }
            //System.out.println("Last : "+result);
            return result;
    
        }
        public static void main(String[] args) 
        {
            Scanner sc = new Scanner(System.in);        
            int testCases = sc.nextInt();
            while(testCases-- >0)
            {
                BigInteger total ;
                total = sc.nextBigInteger();
                BigInteger sum = BigInteger.ZERO;
    //            for(int block =2 ; block<=4 ;block++)
                for(BigInteger block =BigInteger.valueOf(2) ; block.compareTo(BigInteger.valueOf(4))<=0 ;block = block.add(BigInteger.ONE))
                {   
                    BigInteger maxBlock = total.divide(block);
    
                    for(BigInteger color = BigInteger.valueOf(1); color.compareTo(maxBlock) <= 0; color = color.add(BigInteger.ONE))                               {
                      BigInteger black = total.subtract(color.multiply(block));
                      BigInteger tiles = black.add(color);
                      BigInteger combinations = permutation(tiles,color);
                      sum = sum.add(combinations);
                      sum  = sum.mod(BigInteger.valueOf(1000000007));
                    }
                }
                System.out.println(sum);
            }
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        }
    }