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;
}
Time Complexity : O(1)