
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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)xn = Π∞k=1 (1/(1-xk ))
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 Articles
- Count ways to express ‘n’ as sum of odd integers in C++
- Different ways to represent N as the sum of K non-zero integers
- Find two consecutive positive integers, sum of whose squares is 365.
- How can we subtract two positive or negative integers?
- Find two consecutive odd positive integers, sum of whose squares is 970.
- Sum of Two Integers in Python
- Number of arrays of size N whose elements are positive integers and sum is K in C++
- The sum of the squares of two consecutive odd positive integers is 394. Find them.
- Ways to select one or more pairs from two different sets in C++
- C# program to find Union of two or more Dictionaries\n
- Express 18 as the sum of two prime numbers in all possible ways.
- Count of different ways to express N as the sum of 1, 3 and 4 in C++
- Write two integers whose difference is more than $-$6 but these integers should be less than $-$6.
- Find the sum of the first 40 positive integers divisible by 6.
- How to write Python regular expression to get zero or more occurrences within the pattern?\n\n

Advertisements