GCD of two numbers formed by n repeating x and y times
Last Updated :
11 Sep, 2023
Given three positive integer n, x, y. The task is to print Greatest Common Divisor of numbers formed by n repeating x times and number formed by n repeating y times.
0 <= n, x, y <= 1000000000.
Examples :
Input : n = 123, x = 2, y = 3.
Output : 123
Number formed are 123123 and 123123123.
Greatest Common Divisor of 123123 and
123123123 is 123.
Input : n = 4, x = 4, y = 6.
Output : 44
The idea is based on Euclidean algorithm to compute GCD of two number.
Let f(n, x) be a function which gives a number n repeated x times. So, we need to find GCD(f(n, x), f(n, y)).
Let n = 123, x = 3, y = 2.
So, first number A is f(123, 3) = 123123123 and second number B is f(123, 2) = 123123. We know, GCD(A,B) = GCD(A – B, B), using this property we can subtract any multiple of B, say B’ from first A as long as B’ is smaller than A.
So, A = 123123123 and B’ can be 123123000. On subtracting A will became 123 and B remains same.
Therefore, A = A – B’ = f(n, x – y).
So, GCD(f(n, x), f(n, y)) = GCD(f(n, x – y), f(n, y))
We can conclude following,
GCD(f(n, x), f(n, y)) = f(n, GCD(x, y)).
Below is the implementation based on this approach:
CPP
#include<bits/stdc++.h>
using namespace std;
int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
void findgcd( int n, int x, int y)
{
int g = gcd(x,y);
for ( int i = 0; i < g; i++)
cout << n;
}
int main()
{
int n = 123, x = 5, y = 2;
findgcd(n, x, y);
return 0;
}
|
Java
class GFG {
static int gcd( int a, int b) {
if (a == 0 )
return b;
return gcd(b % a, a);
}
static void findgcd( int n, int x, int y) {
int g = gcd(x, y);
for ( int i = 0 ; i < g; i++)
System.out.print(n);
}
public static void main(String[] args) {
int n = 123 , x = 5 , y = 2 ;
findgcd(n, x, y);
}
}
|
Python3
def gcd(a, b):
if (a = = 0 ):
return b
return gcd(b % a, a)
def findgcd(n, x, y):
g = gcd(x, y)
for i in range (g):
print (n)
n = 123
x = 5
y = 2
findgcd(n, x, y)
|
C#
using System;
class GFG {
static int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static void findgcd( int n,
int x, int y)
{
int g = gcd(x, y);
for ( int i = 0; i < g; i++)
Console.Write(n);
}
public static void Main() {
int n = 123, x = 5, y = 2;
findgcd(n, x, y);
}
}
|
PHP
<?php
function gcd( $a , $b )
{
if ( $a == 0)
return $b ;
return gcd( $b % $a , $a );
}
function findgcd( $n , $x , $y )
{
$g = gcd( $x , $y );
for ( $i = 0; $i < $g ; $i ++)
echo ( $n );
}
$n = 123; $x = 5; $y = 2;
findgcd( $n , $x , $y );
?>
|
Javascript
<script>
function gcd(a, b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
function findgcd(n, x, y)
{
let g = gcd(x,y);
for (let i = 0; i < g; i++)
document.write(n);
}
let n = 123, x = 5, y = 2;
findgcd(n, x, y);
</script>
|
Output :
123
Time Complexity: O(log(min(n)) )
Auxiliary Space: O(log(min(n))
Share your thoughts in the comments
Please Login to comment...