# 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 = 51 + 4 = 52 + 3 = 5`
`pairAdditions(6);`
`4 numbers found that add up to 6.0 + 6 = 61 + 5 = 62 + 4 = 63 + 3 = 6`
`pairAdditions(12);`
`7 numbers found that add up to 12.0 + 12 = 121 + 11 = 122 + 10 = 123 + 9 = 124 + 8 = 125 + 7 = 126 + 6 = 12`
`pairAdditions(17);`
`9 numbers found that add up to 17.0 + 17 = 171 + 16 = 172 + 15 = 173 + 14 = 174 + 13 = 175 + 12 = 176 + 11 = 177 + 10 = 178 + 9 = 17`
`pairAdditions(20);`
`11 numbers found that add up to 20.0 + 20 = 201 + 19 = 202 + 18 = 203 + 17 = 204 + 16 = 205 + 15 = 206 + 14 = 207 + 13 = 208 + 12 = 209 + 11 = 2010 + 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)