Number of ways in which N can be represented as the sum of two positive integers
Last Updated :
19 Mar, 2022
Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.
Examples:
Input: N = 7
Output: 3
(1 + 6), (2 + 5) and (3 + 4).
Input: N = 200
Output: 100
Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N – 1), 2 + (N – 2), …, (N – 1) + 1 and (N – 2) + 2. There are N – 1 terms in the series and they appear in identical pairs i.e. (X + Y, Y + X). So the required count will be N / 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int ways( int n)
{
return n / 2;
}
int main()
{
int n = 2;
cout << ways(n);
return 0;
}
|
Java
class GFG
{
static int ways( int n)
{
return n / 2 ;
}
public static void main(String args[])
{
int n = 2 ;
System.out.println(ways(n));
}
}
|
Python3
def ways(n):
return n / / 2
n = 2
print (ways(n))
|
C#
using System;
class GFG
{
static int ways( int n)
{
return n / 2;
}
public static void Main()
{
int n = 2;
Console.WriteLine(ways(n));
}
}
|
Javascript
<script>
function ways(n)
{
return parseInt(n / 2);
}
var n = 2;
document.write(ways(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...