How to print all possible ways to write a number (N) as a sum of two or more positive integers in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class AllWaysToWriteANumberAsSumOfTwoOrMoreInts_CSharp
{
	public static void printList(IList<int> list) {
		if (list.Count != 1) {
			for (int i = 0; i < list.Count; i++) {
				if (i < list.Count - 1) {
					Console.Write(list[i] + " + ");
				}
				else {
					Console.Write(list[i]);
				}
			}
		}
		Console.WriteLine();
	}

	public static void allWaysToWriteANumberAsSumOfTwoOrMoreInts(IList<int> list, int i, int n) {
		if (n == 0) {
			printList(list);
		}

		for (int j = i; j <= n; j++) {
			list.Add(j);
			allWaysToWriteANumberAsSumOfTwoOrMoreInts(list, j, n - j);
			list.RemoveAt(list.Count - 1);
		}
	}

	public static void Main(string[] args)
	{
		int n = 5; // The number

		IList<int> list = new List<int>();

		allWaysToWriteANumberAsSumOfTwoOrMoreInts(list, 1, n);
	}
}



/*
run:
 
1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 2
1 + 1 + 3
1 + 2 + 2
1 + 4
2 + 3
 
*/

 



answered Aug 3, 2024 by avibootz
...