Given three integers A, B and C. You can add or subtract A, B, or 0 any number of times to form new values in the range 0 < final_value ? C. The task is to find the count of such distinct final values possible.
Examples :
Input : A = 2, B = 3, C = 10
Output:10
Possible values are :
0 + 3 – 2 =1
0 + 2 = 2
0 + 3 = 3
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
3+2+2=7
2+2+2+2=8
2+2+2+3=9
3+3+2+2=10
Input : A = 10, B = 2, C = 10
Output: 5
Approach: The idea is to use the GCD g of A and B.
The above approach works Because every distinct possible value is xA+yB
- If A can be written as g×a, B can be written as g×b
- Then, A required final value can be written as xAg+yBg = (x*g*a + y*g*b) = g*(xa+yb)
- Since the maximum value possible is C, therefore C = g*(xa+yb).
- Hence count of possible such values = C/g, which is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int A, int B)
{
if (B == 0)
return A;
else
return gcd(B, A % B);
}
int getDistinctValues( int A, int B, int C)
{
int g = gcd(A, B);
int num_values = C / g;
return num_values;
}
int main()
{
int A = 2;
int B = 3;
int C = 10;
cout << (getDistinctValues(A, B, C));
return 0;
}
|
Java
import java.util.*;
class GFG {
static int gcd( int A, int B)
{
if (B == 0 )
return A;
else
return gcd(B, A % B);
}
static int getDistinctValues( int A, int B, int C)
{
int g = gcd(A, B);
int num_values = C / g;
return num_values;
}
public static void main(String[] args)
{
int A = 2 ;
int B = 3 ;
int C = 10 ;
System.out.println(getDistinctValues(A, B, C));
}
}
|
Python3
def gcd(A, B) :
if (B = = 0 ) :
return A;
else :
return gcd(B, A % B);
def getDistinctValues(A, B, C) :
g = gcd(A, B);
num_values = C / g;
return int (num_values);
A = 2 ;
B = 3 ;
C = 10 ;
print (getDistinctValues(A, B, C));
|
C#
using System;
class GFG
{
static int gcd( int A, int B)
{
if (B == 0)
return A;
else
return gcd(B, A % B);
}
static int getDistinctValues( int A, int B, int C)
{
int g = gcd(A, B);
int num_values = C / g;
return num_values;
}
static void Main()
{
int A = 2;
int B = 3;
int C = 10;
Console.Write(getDistinctValues(A, B, C));
}
}
|
Javascript
<script>
function gcd(A, B)
{
if (B == 0)
return A;
else
return gcd(B, A % B);
}
function getDistinctValues(A, B, C)
{
let g = gcd(A, B);
let num_values = C / g;
return num_values;
}
let A = 2;
let B = 3;
let C = 10;
document.write(getDistinctValues(A, B, C));
</script>
|
Time Complexity : O(log(min(A, B))
Auxiliary Space: O(1)