-6

If you know the result of 1+2+3+..+n, which is n*(n+1)/2.
For example, if the result is 5050, then I can know n is 100. How can I obtain the n. However, you can only calculate the n by only addition and substraction.

And I know how I can get the n i is that I can traverse the natural number from 1 to n, by computing per different 1+2+3+...+n, like 1, 1+2, 1+2+3,...1+2+..+n, then I can check every result to 5050, then I can find the n is 100. But I find that the calculating steps will over 2000 steps, so there is a good algorithm to find the n?
Thanks!.

zhenguoli
  • 2,268
  • 1
  • 14
  • 31

3 Answers3

3

Note that:

1 + 2 + ... + N = V = N(N+1)/2

Can be rewritten as:

N^2 + N - 2V = 0

The value you are looking for is thus:

(-1+sqrt(1+4*2*value))/2;

That is one of the zeros of the given quadratic equation.


In C++ you can use a function like this:

int rev(int value) {
    return (-1+std::sqrt(1+4*2*value))/2;
}
skypjack
  • 49,335
  • 19
  • 95
  • 187
2

Only by addition and subtraction... Simply add numbers from 1 and check whether the sum is the given number.

In pseudocode. Given 5050.

number := 5050
next, sum := 0
while sum <= number
  next := next + 1
  sum := sum + next
return next
Grzegorz Górkiewicz
  • 4,496
  • 4
  • 22
  • 38
0

Suppose 1 + 2 + .. + n = n*(n+1)/2 = r (r is known n and is unknown).

Now we want to know the positive value of n for which the above equation is satisfied.

Theoretical method

We have, n^2+n=2*r => (n+1/2)^2 = 2*r + 1/4 => n + 1/2 = sqrt(2*r+1/4) (taking only the +ve sqrt since n>0) => n = sqrt(2*r+1/4) - 1/2 For example, r=55 => n =10, which can be found in O(1) time by plugging the value of r.

Numerical method

Now, we may fidn the solution numerically as well, by finding the positive root of the equation (n^2+n)/2-r=0. If r=55, the graph of the quadratic equation looks like the following, the root can be found out numerically by using bisection or newton-raphson like numerical methods. The following graph of the quadratic polynomial shows that n=10 for r=55.

enter image description here

Community
  • 1
  • 1
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63