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" ; }