Summation inside a range

25 Views Asked by At

I was a bit bored so I decided to create a program with a function that takes three variables:

Upper, Lower, and Target.

What the function does from that is loops through each integer from the range lower->upper, and in that loop, it has yet another loop that does that same thing.

So for every increment of the first loop, it goes through every number in that range again.

So that gives me two new variables, let's call them k and n.

Then I have an IF-statement that checks if k+n=Target, if so, it adds it to an array.

(I hope you understood that part)

Here is an example run of the program.

As you maybe have noticed the number of ways it can be done within that range is equal to the Target - 1.

Can somebody explain to me why this is the case?

I am sorry if my explanation was bad, English isn't my main language.

Here is the code-snippet, in c#:

public static void additions(Int64 upper, Int64 lower, Int64 target)
    {
        for (Int64 i = lower; i <= upper; i++)
        {
            for (Int64 k = lower; k <= upper; k++)
            {
                if (i + k == target)
                    results.Add(i.ToString() + " " + k.ToString());
            }
        }
    }