Count ways to divide C in two parts and add to A and B to make A strictly greater than B
Last Updated :
22 Mar, 2022
Given three integers A, B and C, the task is to count the number of ways to divide C into two parts and add to A and B such that A is strictly greater than B.
Examples:
Input: A = 5, B = 3, C = 4
Output: 3
The possible values of A and B after dividing C are:
A = 7, B = 5 where C is divided into 2 and 2.
A = 8, B = 4 where C is divided into 3 and 1.
A – 9, B = 3 where C is divided into 4 and 0.
Input: A = 3, B = 5, C = 5
Output: 2
Approach: On observing carefully, the following relation is formed for this problem.
- Let addA and addB be added to A and B respectively.
- Therefore, addA + addB = C and it should satisfy the inequality A + addA > B + addB.
- Now, since addB = C – addA and put it in the inequality:
A + addA > B + (C - addA)
or, 2addA > C + B - A
or, 2addA >= C + B - A + 1
or, addA >= (C + B - A + 1) / 2
- Since addA must be non negative, addA = max(0, (C + B – A + 1) / 2).
- The division should be ceiling division, thus we can rewrite as addA = max(0, (C + B – A + 2) / 2).
- Let this value be equal to minAddA. Since all integer values addA from [minAddA, C], satisfies the relation A + addA > B + addB, so the required number of ways is equal to max(0, C – minAddA + 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countWays( int A, int B, int C)
{
int minAddA = max(0, (C + B - A + 2) / 2);
int count_ways = max(C - minAddA + 1, 0);
return count_ways;
}
int main()
{
int A = 3, B = 5, C = 5;
cout << countWays(A, B, C);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countWays( int A, int B, int C)
{
int minAddA = Math.max( 0 , (C + B - A + 2 ) / 2 );
int count_ways = Math.max(C - minAddA + 1 , 0 );
return count_ways;
}
public static void main(String args[])
{
int A = 3 , B = 5 , C = 5 ;
System.out.println(countWays(A, B, C));
}
}
|
Python3
def countWays(A, B, C):
minAddA = max ( 0 , (C + B - A + 2 ) / / 2 )
count_ways = max (C - minAddA + 1 , 0 )
return count_ways
A = 3
B = 5
C = 5
print (countWays(A, B, C))
|
C#
using System;
class GFG
{
static int countWays( int A, int B, int C)
{
int minAddA = Math.Max(0, (C + B - A + 2) / 2);
int count_ways = Math.Max(C - minAddA + 1, 0);
return count_ways;
}
public static void Main(String[] args)
{
int A = 3, B = 5, C = 5;
Console.Write(countWays(A, B, C));
}
}
|
Javascript
<script>
function countWays(A, B, C)
{
var minAddA = Math.max(0, parseInt((C + B - A + 2) / 2));
var count_ways = Math.max(C - minAddA + 1, 0);
return count_ways;
}
var A = 3, B = 5, C = 5;
document.write( countWays(A, B, C));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...