Store the GCD of the length of the Strings
int gcd = GCD ( a . length ( ) , b . length ( ) ) ; if ( a . substring ( 0 , gcd ) . equals ( b . substring ( 0 , gcd ) ) ) { int x = ( ( int ) b . length ( ) / gcd ) ; int y = ( ( int ) a . length ( ) / gcd ) ; String r = " " , s = " " ; while ( x -- > 0 ) s += a ; while ( y -- > 0 ) r += b ; if ( s . equals ( r ) ) return a . substring ( 0 , gcd ) ; } return " - 1" ; }