Ways to write n as sum of two or more positive integers
Last Updated :
11 Sep, 2023
For a given number n > 0, find the number of different ways in which n can be written as a sum of two or more positive integers.
Examples:
Input : n = 5
Output : 6
Explanation : All possible six ways are :
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
Input : 4
Output : 4
Explanation : All possible four ways are :
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
This problem can be solved in a similar fashion as coin change problem, the difference is only that in this case we should iterate for 1 to n-1 instead of particular values of coin as in coin-change problem.
C++
#include <bits/stdc++.h>
using namespace std;
int countWays( int n)
{
int table[n+1];
memset (table, 0, sizeof (table));
table[0] = 1;
for ( int i=1; i<n; i++)
for ( int j=i; j<=n; j++)
table[j] += table[j-i];
return table[n];
}
int main()
{
int n = 7;
cout << countWays(n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int countWays( int n)
{
int table[] = new int [n + 1 ];
Arrays.fill(table, 0 );
table[ 0 ] = 1 ;
for ( int i = 1 ; i < n; i++)
for ( int j = i; j <= n; j++)
table[j] += table[j - i];
return table[n];
}
public static void main (String[] args)
{
int n = 7 ;
System.out.print(countWays(n));
}
}
|
Python3
def CountWays(n):
table = [ 0 ] * (n + 1 )
table[ 0 ] = 1
for i in range ( 1 , n ):
for j in range (i , n + 1 ):
table[j] + = table[j - i]
return table[n]
def main():
n = 7
print (CountWays(n))
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG {
static int countWays( int n)
{
int []table = new int [n+1];
for ( int i = 0; i < table.Length; i++)
table[i] = 0;
table[0] = 1;
for ( int i = 1; i < n; i++)
for ( int j = i; j <= n; j++)
table[j] += table[j-i];
return table[n];
}
public static void Main()
{
int n = 7;
Console.Write(countWays(n));
}
}
|
PHP
<?php
function countWays( $n )
{
$table = array_fill (0, $n + 1, NULL);
$table [0] = 1;
for ( $i = 1; $i < $n ; $i ++)
for ( $j = $i ; $j <= $n ; $j ++)
$table [ $j ] += $table [ $j - $i ];
return $table [ $n ];
}
$n = 7;
echo countWays( $n );
?>
|
Javascript
<script>
function countWays(n)
{
let table = new Array(n + 1);
for (let i = 0; i < n + 1; i++)
{
table[i]=0;
}
table[0] = 1;
for (let i = 1; i < n; i++)
for (let j = i; j <= n; j++)
table[j] += table[j - i];
return table[n];
}
let n = 7;
document.write(countWays(n));
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...