# GCD of digits of a given number

Given a number n, find GCD of its digits.

Examples:

```Input  : 345
Output : 1
GCD of 3, 4 and 5 is 1.

Input  : 2448
Output : 2
GCD of 2, 4, 4 and 8 is 2
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We traverse the digits of number one by one using below loop

```digit = n mod 10;
n  = n / 10; ```

While traversing digits, we keep track of current GCD and keep updating GCD by finding GCD of current digit with current GCD.

```// CPP program to find GCD of digits of a number
#include<iostream>
#include<algorithm>
using namespace std;

int digitGCD(int n)
{
int gcd = 0;
while (n > 0)
{
gcd = __gcd(n%10, gcd);

// If at point GCD becomes 1,
// return it
if (gcd == 1)
return 1;

n = n/10;
}
return gcd;
}

// driver code
int main()
{
long n = 2448;
cout << digitGCD(n);
return 0;
}
```

Output:

`2`

This article is contributed by Dibyendu Roy Chaudhuri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
3 Average Difficulty : 3/5.0
Based on 2 vote(s)