"Sherlock and the Beast" challenge in Java I have been trying to solve the following problem on hackerrank.com, but when I submit the code it shows unsuccessful submission due to timeout. Can anyone help me out?

Sherlock and the Beast

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class test {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int t = in.nextInt();
    int a[] = new int[t];


    // reading test cases

    for( int i=0; i&lt;t; i++){
        a[i] = in.nextInt();
    }       

    int n = 0;  // length of decent string


    boolean break1 ; // for breaking 2 for loops after getting the output for each test case

    for( int i=0; i&lt;t; i++){
        n = a[i];
        int testx = n/3;
        int testy = n/5;
        break1 = false;

        for( int x = testx; x &gt;= 0; x--){

            for( int y = testy; y &gt;= 0; y--){

                if( ( x==0 &amp;&amp; y== 0 ) ){

                    System.out.println("-1");

                    break1 = true;                      
                    break;
                }

                else if ( n % (3*x+5*y) == 0){                                          

                    System.out.println( getdecentString(x, y) );

                    break1 = true;
                    break;

                }                                   

            }

            if ( break1 == true)
                break;

        }       
    }



}   


// function to generate decentString

static String getdecentString(int x, int y){  
    String decentString = "";
    x = 3*x;
    y = 5*y;

    for( int j=1; j &lt;= x; j++)
        decentString =  decentString + "5";

    for( int k=1; k &lt;= y; k++)
        decentString =  decentString + "3"; 

    return decentString;

}       


}
As Robert pointed out, your code spends a lot of time in getdecentString. A faster way to generate Strings would be to use the StringBuilder class, e.g.:

StringBuilder decentString = new StringBuilder();
...
for ( int j = 1; j &lt;= x; j++ )
{
    decentString.append( "5" );
}
...
return decentString.toString();