Created
September 13, 2018 11:23
-
-
Save junaidrahim/32b39567475d2dd40b83b25ec540c8a5 to your computer and use it in GitHub Desktop.
GCD of n numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <cstring> | |
using namespace std; | |
vector<int> parse_string_to_int(string input,const char* t){ // "1,2,3" => [1,2,3] | |
char array[input.length()+1]; | |
strcpy(array, input.c_str()); // converting the string into a char[] | |
vector<int> result; | |
char* token = strtok(array,t); | |
while(token!=NULL){ | |
string s(token); //converting the char* token to a string again | |
result.push_back(stoi(s)); | |
token = strtok(NULL,t); | |
} | |
return result; | |
} | |
// Returns gcd of 2 numbers | |
int gcd(int x, int y){ | |
while(x!=y){ | |
if (x>y) | |
x = x-y; | |
else | |
y = y-x; | |
} | |
return x; | |
} | |
int main(){ | |
string input; | |
cout << "Enter the numbers(seperate by commas): "; | |
cin >> input ; | |
const char* t = ","; | |
vector<int> numbers_vector = parse_string_to_int(input,t); | |
int k = numbers_vector[0]; | |
for(int i=1; i<numbers_vector.size(); i++){ | |
k = gcd(k,numbers_vector[i]); | |
} | |
cout << "GCD is " << k << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment