GCD of digits of a given number
Last Updated :
17 Feb, 2023
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
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.
C++
#include<iostream>
#include<algorithm>
using namespace std;
int digitGCD( int n)
{
int gcd = 0;
while (n > 0)
{
gcd = __gcd(n%10, gcd);
if (gcd == 1)
return 1;
n = n/10;
}
return gcd;
}
int main()
{
long n = 2448;
cout << digitGCD(n);
return 0;
}
|
Java
class GFG
{
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
static int digitGCD( int n)
{
int gcd = 0 ;
while (n > 0 )
{
gcd = __gcd(n % 10 , gcd);
if (gcd == 1 )
return 1 ;
n = n / 10 ;
}
return gcd;
}
public static void main (String[] args)
{
int n = 2448 ;
System.out.print(digitGCD(n));
}
}
|
Python3
def __gcd(a,b):
return a if (b = = 0 ) else __gcd(b, a % b)
def digitGCD(n):
gcd = 0
while (n > 0 ):
gcd = __gcd(n % 10 , gcd)
if (gcd = = 1 ):
return 1
n = n / / 10
return gcd
n = 2448
print (digitGCD(n))
|
C#
using System;
class GFG {
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
static int digitGCD( int n)
{
int gcd = 0;
while (n > 0)
{
gcd = __gcd(n % 10, gcd);
if (gcd == 1)
return 1;
n = n / 10;
}
return gcd;
}
public static void Main ()
{
int n = 2448;
Console.Write(digitGCD(n));
}
}
|
PHP
<?php
function __gcd( $a , $b )
{
return $b == 0 ? $a :
__gcd( $b , $a % $b );
}
function digitGCD( $n )
{
$gcd = 0;
while ( $n > 0)
{
$gcd = __gcd( $n % 10, $gcd );
if ( $gcd == 1)
return 1;
$n = $n / 10;
}
return $gcd ;
}
$n = 2448;
echo digitGCD( $n );
?>
|
Javascript
<script>
function __gcd(a, b)
{
return b == 0 ? a : __gcd(b, a % b);
}
function digitGCD(n)
{
var gcd = 0;
while (n > 0)
{
gcd = __gcd(n % 10, gcd);
if (gcd == 1)
return 1;
n = parseInt(n / 10);
}
return gcd;
}
var n = 2448;
document.write(digitGCD(n));
</script>
|
Output :
2
Time complexity: O(logn)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...