Store the GCD of the length of the strings
int gcd = GCD ( a . size ( ) , b . size ( ) ) ; if ( a . substr ( 0 , gcd ) == b . substr ( 0 , gcd ) ) { int x = ( ( int ) b . size ( ) / gcd ) ; int y = ( ( int ) a . size ( ) / gcd ) ; string r = " " , s = " " ; while ( x -- ) s += a ; while ( y -- ) r += b ; if ( s == r ) return a . substr ( 0 , gcd ) ; } return " - 1" ; }