- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Ways to write N as sum of two or more positive integers in C++

In this problem, we are given an integer n. Our task is to find the total number of ways in can be expressed as sum of two or more positive integers.

Let’s take an example to understand the problem,

## Input

N = 4

## Output

5

## Explanation

4 can be written as the sum in these ways, 4, 3+1, 2+2, 2+1+1, 1+1+1+1

To solve this problem, we will use Euler’s recurrence formula. For a number n the total number of ways it can be generated p(n) by,

Σ^{∞}n=0 p(n)x^{n}= Π^{∞}k=1 (1/(1-x^{k}))

Using this formula, we will derive formula for p(n),p(n) = p(n-1) + p(n-2) - p(n-5) - p(n-7) + … + (-1)^{(k-1)}((k(3k-1))/2)

Program to illustrate the implementation of our solution,

## Example

#include <bits/stdc++.h> using namespace std; long long postiveSum(int n){ vector<long long> p(n + 1, 0); p[0] = 1; for (int i = 1; i <= n; ++i) { int k = 1; while ((k * (3 * k - 1)) / 2 <= i) { p[i] += (k % 2 ? 1 : -1) * p[i - (k * (3 * k - 1)) / 2]; if (k > 0) k *= -1; else k = 1 - k; } } return p[n]; } int main(){ int N = 12; cout<<"The number of ways "<<N<<" can be written as sum of two or more positive numbers is " <<postiveSum(N); return 0; }

## Output

The number of ways 12 can be written as sum of two or more positive numbers is 77

- Related Questions & Answers
- Count ways to express ‘n’ as sum of odd integers in C++
- Sum of Two Integers in Python
- Number of arrays of size N whose elements are positive integers and sum is K in C++
- Ways to select one or more pairs from two different sets in C++
- Count of different ways to express N as the sum of 1, 3 and 4 in C++
- Find n positive integers that satisfy the given equations in C++
- Check if N can be represented as sum of integers chosen from set {A, B} in Python
- Program to check n can be shown as sum of k or not in Python
- Find N Unique Integers Sum up to Zero in C++
- C++ Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
- Integers have sum of squared divisors as perfect square in JavaScript
- C# program to find Union of two or more Dictionaries
- C# program to find Union of two or more Lists
- Python program to find Union of two or more Lists?
- Count ways to express a number as sum of powers in C++

Advertisements