Count the ways to write N as a sum of three numbers

Updated

Given a positive integer N, count number of ways to write N as a sum of three numbers.

Examples :

Input : N = 4
Output : 3
Explanation :
( 1 + 1 + 2 ) = 4 ( 1 + 2 + 1 ) = 4 ( 2 + 1 + 1 ) = 4

Input : N = 5
Output : 6
Explanation :
( 1 + 1 + 3 ) = 5 ( 1 + 3 + 1 ) = 5 ( 3 + 1 + 1 ) = 5 ( 1 + 2 + 2 ) =
5 ( 2 + 2 + 1 ) = 5 ( 2 + 1 + 2 ) = 5

Approach :

If we take a closer look at the pattern, we can observe that a series will be formed for n > = 2 3, 6, 10, 15, 21………….which is the sum of first n-1 natural numbers

Implementation :

#include<bits/stdc++.h>
using namespace std;
 
void ans(int n)
{ 
  if(n<=2)
  cout<<"n cannot be represented as sum of 3 numbers";
  else
  cout<<(n-1)*(n-2)/2;
}
 
int main() 
{ 
    int  n = 4;
    ans(n); 
    return 0; 
} 

Output :

3

Time Complexity : O(1)

Comment
Mithlesh Upadhyay Published 24 Nov 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials