Number of Non-achievable Scores of the form Ax+By=C
Last Updated :
30 Oct, 2023
A fellow Geek plays a video game. He has 2 co-prime integers A and B (Constraints: 1 <= A <= B <= 1e9). He wants to know about the total number of scores that are less than A*B and not achievable by him. He can achieve a score of Z if that particular number can be expressed as AX+BY = Z (where X and Y are whole numbers i.e. X >= 0 and Y >= 0). Help your fellow geek to determine the total number of scores not achievable by him.
Examples:
Input: A = 3, B = 5
Output: 4
Explanation: He can’t achieve a score of 1, 2, 4, 7. Hence the answer is 4. He can express 3 as 3*1+5*0, 5 as 3*0+5*1, 6 as 3*2+5*0, 8 as 3*1+5*1, 9 as 3*3+5*0, 10 as 3*0+5*2, 11 as 3*2 +5*1, 12 as 3*4 +5*0, 13 as 3*1+5*2, 14 as 3*3+5*1 and so on.
Input: A = 2, B = 7
Output: 3
Explanation: He can’t achieve the score of [1, 3,5]. Hence the answer is 3. He can express 2 as:
2*1+7*0 , 4 as 2*2+7*0 , 6 as 2*3+7*0, 7 as 2*0+7*1 and so on.
Approach: To solve the problem follow the below idea:
The idea is that we know the LCM of two Co-prime numbers is simply their product (since their GCD=1).
Follow the steps to solve the problem:
- Let the LCM be X = A*B.
- So there are a total of X – (X/A + X/B – 1 [since A*B is divisible by both A and B] ) numbers, which are neither divisible by A nor B.
- Let Z = A*B-A-B+1 = (A-1)*(B-1)
- For any integer k, exactly one of (k, A*B-B-A-k) can be expressed as the AX+BY. (from Chicken McNugget Theorem)
- Hence there are Z/2 numbers that can’t be expressed in the form AX+BY.
- So there is direct O(1 ) solution which is equals to (A-1)*(B-1)/2
Below is the implementation of the above idea:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 3, b = 5;
cout << ((a - 1) * (b - 1)) / 2;
return 0;
}
|
Java
public class Main {
public static void main(String[] args) {
int a = 3 , b = 5 ;
System.out.println(((a - 1 ) * (b - 1 )) / 2 );
}
}
|
Python3
if __name__ = = "__main__" :
a = 3
b = 5
print (((a - 1 ) * (b - 1 )) / / 2 )
|
C#
using System;
class Program
{
static void Main( string [] args)
{
int a = 3, b = 5;
Console.WriteLine(((a - 1) * (b - 1)) / 2);
}
}
|
Javascript
let a = 3;
let b = 5;
console.log(((a - 1) * (b - 1)) / 2);
|
Time Complexity: O(1)
Auxiliary Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...