Smallest string divisible by two given strings | Java program for above approach ; Function to calculate GCD of two numbers ; Function to calculate LCM of two numbers ; Function to find the smallest string which is divisible by strings S and T ; Store the length of both strings ; Store LCM of n and m ; Temporary strings to store concatenated strings ; Concatenate s1 ( l / n ) times ; Concatenate t1 ( l / m ) times ; If s1 and t1 are equal ; Otherwise , print - 1 ; Driver code
import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } static void findSmallestString ( String s , String t ) { int n = s . length ( ) , m = t . length ( ) ; int l = lcm ( n , m ) ; String s1 = " " , t1 = " " ; for ( int i = 0 ; i < l / n ; i ++ ) { s1 += s ; } for ( int i = 0 ; i < l / m ; i ++ ) { t1 += t ; } if ( s1 . equals ( t1 ) ) { System . out . println ( s1 ) ; } else { System . out . println ( - 1 ) ; } } public static void main ( String [ ] args ) { String S = " baba " , T = " ba " ; findSmallestString ( S , T ) ; } }