Number Pair Additions In PHP

16th April 2011 - 4 minutes read time

I was helping my son out with his maths homework today and we came across a question that asked him to find some combinations of two numbers that added up to a given number (he is only 6 so this was good maths practice). This got me to thinking about how to calculate all possible ways in which two numbers could be added together to make another number.

The only rule had to be in there was that doing things like 1+11=12 and 11+1=12 are basically the same thing and so would be cheating. In which case I realised that it would only be necessary to use half of the numbers when creating the list, so for the number 12 every combination can be found using the numbers 0-6 because after this we start duplicating the sums, just swapping the order.

Here is the function I came up with.


function pairAdditions($number) {
  $count = 0;
  $sums = '';
  foreach (range(0, ($number/2)) as $part) {
    ++$count;
    $sums .= $part . ' + ' . ($number - $part) . ' = ' . $number . "\n";
  }
  print $count . " numbers found that add up to " . $number . ".\n" . $sums;
}

The more observant of you might have noticed that the range() function above might be given an odd number every now and then. This doesn't matter as the default step amount in the range() function is 1, so it will only go up to the highest whole number when creating your array.

I have run a few tests to show the output that the function produces.

pairAdditions(5);

3 numbers found that add up to 5.
0 + 5 = 5
1 + 4 = 5
2 + 3 = 5
pairAdditions(6);

4 numbers found that add up to 6.
0 + 6 = 6
1 + 5 = 6
2 + 4 = 6
3 + 3 = 6
pairAdditions(12);

7 numbers found that add up to 12.
0 + 12 = 12
1 + 11 = 12
2 + 10 = 12
3 + 9 = 12
4 + 8 = 12
5 + 7 = 12
6 + 6 = 12
pairAdditions(17);

9 numbers found that add up to 17.
0 + 17 = 17
1 + 16 = 17
2 + 15 = 17
3 + 14 = 17
4 + 13 = 17
5 + 12 = 17
6 + 11 = 17
7 + 10 = 17
8 + 9 = 17
pairAdditions(20);

11 numbers found that add up to 20.
0 + 20 = 20
1 + 19 = 20
2 + 18 = 20
3 + 17 = 20
4 + 16 = 20
5 + 15 = 20
6 + 14 = 20
7 + 13 = 20
8 + 12 = 20
9 + 11 = 20
10 + 10 = 20

This might seem like simple stuff, but it amazed my 6 year old and helped him check his answers afterwards :)

Comments

Permalink

Hi Philip,

You come with a nice soultion. that soundz good. but why dnt u explian in detail abt that function , and how the $part like variables helps for that function?

please send me the full length code that how it works?

thank you

Vamsi (Mon, 02/27/2012 - 14:55)

Add new comment

The content of this field is kept private and will not be shown publicly.