Find the GCD of an array made up of numeric strings | CPP program for the above approach ; Recursive function to return gcd of A and B ; Base case ; Length of A is greater ; Calculate GCD ; Store the GCD of the length of the strings ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int lena , int lenb ) { if ( lena == 0 ) return lenb ; if ( lenb == 0 ) return lena ; if ( lena == lenb ) return lena ; if ( lena > lenb ) return GCD ( lena - lenb , lenb ) ; return GCD ( lena , lenb - lena ) ; } string StringGCD ( string a , string b ) { 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" ; } int main ( ) { string a = " geeksgeeks " ; string b = " geeks " ; cout << ( StringGCD ( a , b ) ) ; }