Check if N can be obtained by repetitive addition or subtraction of two given numbers
Last Updated :
06 Apr, 2021
Given three positive integers N, A, and B, the task is to check if it is possible to obtain N by adding or subtracting A and B multiple times.
Examples:
Input: N = 11, A = 2, B = 5
Output: YES
Explanation: 11 = 5 + 5 + 5 – 2 -2
Input: N = 11, A = 2, B = 4
Output: NO
Explanation: Not possible to obtain 11 from 2 and 4 only.
Approach:
Follow the steps below to solve the problem:
- The task is to check if it is possible to add or subtract A and B multiple times and obtain N as the end result.
- Hence, in terms of linear equation, it can be written as:
Ax + By = N,
where x and y represent the number of times A and B are added or subtracted. Negative x represents A is subtracted x times and similarly, negative y represents B is subtracted y times
- Now, the aim is to find the integral solutions for the above equation. Here, it is quite valid to use Extended Euclid Algorithm which says that the solutions exist if and only if N % gcd(a, b) is 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int N, int a, int b)
{
int g = __gcd(a, b);
if (N % g == 0)
return true ;
else
return false ;
}
int main()
{
int N = 11, a = 2;
int b = 5;
if (isPossible(N, a, b))
cout << "YES" ;
else
cout << "NO" ;
}
|
Java
class GFG{
public static int gcd( int a, int b)
{
if (b == 0 )
return a;
return gcd(b, a % b);
}
public static boolean isPossible( int N, int a,
int b)
{
int g = gcd(a, b);
if (N % g == 0 )
return true ;
else
return false ;
}
public static void main(String[] args)
{
int N = 11 , a = 2 ;
int b = 5 ;
if (isPossible(N, a, b))
System.out.print( "YES" );
else
System.out.print( "NO" );
}
}
|
Python3
def gcd(a, b):
if (b = = 0 ):
return a
return gcd(b, a % b)
def isPossible(N, a, b):
g = gcd(a, b)
if (N % g = = 0 ):
return True
else :
return False
N = 11
a = 2
b = 5
if (isPossible(N, a, b) ! = False ):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG{
static int gcd( int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static bool isPossible( int N, int a,
int b)
{
int g = gcd(a, b);
if (N % g == 0)
return true ;
else
return false ;
}
public static void Main()
{
int N = 11, a = 2;
int b = 5;
if (isPossible(N, a, b))
Console.Write( "YES" );
else
Console.Write( "NO" );
}
}
|
Javascript
<script>
function gcd(a, b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
function isPossible(N, a, b)
{
var g = gcd(a, b);
if (N % g == 0)
return true ;
else
return false ;
}
var N = 11, a = 2;
var b = 5;
if (isPossible(N, a, b))
document.write( "YES" );
else
document.write( "NO" );
</script>
|
Time Complexity: O(log(min(A, B))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...