Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmNumber of ways in which N can be represented as the sum...

Number of ways in which N can be represented as the sum of two positive integers

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:
(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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the number of
// distinct ways to represent n
// as the sum of two integers
int ways(int n)
{
    return n / 2;
}
 
// Driver code
int main()
{
    int n = 2;
 
    cout << ways(n);
 
    return 0;
}


Java




// Java implementation of the approach
 
class GFG
{
     
    // Function to return the number of
    // distinct ways to represent n
    // as the sum of two integers
    static int ways(int n)
    {
        return n / 2;
    }
     
    // Driver code
    public static void main(String args[])
    {
        int n = 2;
     
        System.out.println(ways(n));
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the approach
 
# Function to return the number of
# distinct ways to represent n
# as the sum of two integers
def ways(n):
    return n // 2
 
# Driver code
n = 2
 
print(ways(n))
 
# This code is contributed by Mohit Kumar


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the number of
// distinct ways to represent n
// as the sum of two integers
static int ways(int n)
{
    return n / 2;
}
 
// Driver code
public static void Main()
{
    int n = 2;
 
    Console.WriteLine(ways(n));
}
}
 
// This code is contributed by Nidhi_Biet


Javascript




<script>
 
 
// Javascript implementation of the approach
 
// Function to return the number of
// distinct ways to represent n
// as the sum of two integers
function ways(n)
{
    return parseInt(n / 2);
}
 
// Driver code
var n = 2;
document.write(ways(n));
 
// This code is contributed by noob2000.
</script>


Output: 

1

 

Time Complexity: O(1)

Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments