Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all numbers that add up to a number

Tags:

I'm trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have:

1, 4 2, 3 

Or for 3 integers that make 6:

1, 1, 4 1, 2, 3 2, 2, 2 

I only need whole numbers not including 0 and it only needs to work on up to about 15 in a set and 30 max. number.

I'm not even sure if this has a term mathematically. It's similar to factorisation I guess?

like image 680
Sam Machin Avatar asked Jan 14 '10 16:01

Sam Machin


People also ask

What is all the numbers from 1 to 50 added up?

And hence the sum of the first 50 natural numbers to be 1275.

What do you call numbers that add up to another number?

The two numbers being added together are called addends or summands.

How do you find the sum of all numbers between 1 and n?

Sum of first n positive integers = n(n + 1)/2, where n is the total number of integers. Let us see the applications of the sum of integers formula along with a few solved examples.

How do you find the sum of numbers?

We can obtain the sum of digits by adding the digits of a number. We can ignore the digit's place values to find the digit sum. For example, the digit sum of 185 is 1 + 8 + 5 or 14.

What are all the numbers from 1 to 100 added?

Natural numbers are counting numbers only starting from 1. The sum of natural numbers 1 to 100 is 5050.

How do you sum all integers?

Using the Formula(n / 2)(first number + last number) = sum, where n is the number of integers. Let's use the example of adding the numbers 1-100 to see how the formula works.


2 Answers

Here is one way to solve this problem:

def sum_to_n(n, size, limit=None):     """Produce all lists of `size` positive integers in decreasing order     that add up to `n`."""     if size == 1:         yield [n]         return     if limit is None:         limit = n     start = (n + size - 1) // size     stop = min(limit, n - size + 1) + 1     for i in range(start, stop):         for tail in sum_to_n(n - i, size - 1, i):             yield [i] + tail 

You can use it like this.

for partition in sum_to_n(6, 3):     print partition  [2, 2, 2] [3, 2, 1] [4, 1, 1] 
like image 119
Jason Orendorff Avatar answered Sep 24 '22 07:09

Jason Orendorff


There's a snippet here:

from itertools import combinations, chain  def sum_to_n(n):     'Generate the series of +ve integer lists which sum to a +ve integer, n.'     from operator import sub     b, mid, e = [0], list(range(1, n)), [n]     splits = (d for i in range(n) for d in combinations(mid, i))      return (list(map(sub, chain(s, e), chain(b, s))) for s in splits) 

Use it like this:

for p in sum_to_n(4):         print p 

Outputs:

 [4] [1, 3] [2, 2] [3, 1] [1, 1, 2] [1, 2, 1] [2, 1, 1] [1, 1, 1, 1] 
like image 24
jbochi Avatar answered Sep 21 '22 07:09

jbochi