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