Count ways to express a number as sum of exactly two numbers
Given a positive integer N. The task is to find the number of ways in which you can express N as a sum of exactly two numbers A and B (N = A + B) where A > 0, B > 0 and B > A.
Examples:
Input: N = 8
Output: 3
Explanation:
N = 8 can be expressed as (1, 7), (2, 6), (3, 5)
Input: N = 14
Output: 6
Approach:
- An observation here is that for every number N, if we take a number A which is less than N/2, then there must be a number B which is greater than N/2 and A + B = N.
- This leads to a simple solution of finding the count of numbers for either B or A. Hence, the floor value of (N-1)/2 will lead to the solution.
C++
#include <bits/stdc++.h>
using namespace std;
int CountWays( int n)
{
int ans = (n - 1) / 2;
return ans;
}
int main()
{
int N = 8;
cout << CountWays(N);
}
|
Java
class GFG{
static int CountWays( int n)
{
int ans = (n - 1 ) / 2 ;
return ans;
}
public static void main(String[] args)
{
int N = 8 ;
System.out.print(CountWays(N));
}
}
|
Python3
def CountWays(n) :
ans = (n - 1 ) / / 2
return ans
N = 8
print (CountWays(N))
|
C#
using System;
class GFG{
static int CountWays( int n)
{
int ans = (n - 1) / 2;
return ans;
}
public static void Main()
{
int N = 8;
Console.Write(CountWays(N));
}
}
|
Javascript
<script>
function CountWays(n)
{
let ans = Math.floor((n - 1) / 2);
return ans;
}
let N = 8;
document.write(CountWays(N));
</script>
|
Time complexity: O(1)
Auxiliary space: O(1) because it is using constant space for variable
Last Updated :
18 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...