Find the GCD of an array made up of numeric strings


In this article, we'll delve into an intriguing problem related to arrays and string manipulation in C++. The problem we're examining today is "Find the GCD (Greatest Common Divisor) of an array made up of numeric strings". This problem is a great way to hone your skills in string manipulation, arrays, and number theory.

Problem Statement

Given an array of strings where each string represents a positive integer, our task is to find the Greatest Common Divisor (GCD) of all these integers.

C++ Solution Approach

We'll convert each string to an integer and calculate the GCD of all these integers. To calculate the GCD, we can use Euclid's algorithm, which is an efficient way to find the GCD of two numbers.

Example

Here's the C++ code that solves the problem

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int gcd(int a, int b) {
   if (b == 0) {
      return a;
   }
   return gcd(b, a % b);
}

int findGCD(vector<string>& arr) {
   int result = stoi(arr[0]);
   
   for(int i = 1; i < arr.size(); i++) {
      result = gcd(result, stoi(arr[i]));
   }
   
   return result;
}

int main() {
   vector<string> arr = {"42", "84", "126", "168"};
   int result = findGCD(arr);
   cout << "The GCD of the array is: " << result << endl;
   return 0;
}

Output

The GCD of the array is: 42

Explanation with a Test Case

Let's take the array of strings {"42", "84", "126", "168"}.

When we pass this array to the findGCD function, it first converts the first string to an integer and stores it in the variable result.

Then it iterates over the rest of the array, converting each string to an integer and updating result to be the GCD of result and the current integer.

For the given array, the GCD of all the integers is 42. So, the function will return 42.

Conclusion

This problem demonstrates how we can manipulate strings and use number theory to solve complex problems in C++. It's an excellent problem to practice your C++ coding skills and to understand Euclid's algorithm for finding the GCD of two numbers.

Updated on: 17-May-2023

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements