[Solved] obtain a number by addition or subtraction of consecutive natural numbers


The solution is :

for n=1: = 1
for n=2: = 1+2 => 1+2+3 => 1-2+3 
for n=3: = 1+2
for n=4: = 1+2+3 => -1+2+3
for n=5: = 1+2+3 => 1+2+3+4-5
for n=6: = 1+2+3
for n=7: = 1+2+3+4=>1+2+3+4+5=>1+2+3-4+5
for any n, first calculate the S(k)=1+2+3+...+k

where S(k)>n and x=S(k)-n is an even number. Then go flip the + of x/2 to -.

S(k) = (1+k)*k/2 > n
=> k*k + k -2n > 0
=> k > (-1 + sqrt(1+8n))/2

eg, n=7, k > 3.2, then k=4, S(4) = 10, 10-7=3, it’s odd, so k=5, S(5)=15, x=15-7=8, 8/2=4, flip the sign of 4, we got 1+2+3-4+5 = 7

in some cases, Sk-n is odd, but S(k+1)-n is also odd, in this case, we need to use S(k+2).
The code is as follow :

public void step() {
        k = (int)Math.ceil(((-1 + Math.sqrt(1 + 8 * n)) / 2));
        int Sk = (1 + k) * k / 2;
        if ((Sk - n) % 2 != 0) {
            k++;
            Sk = (1 + k) * k / 2;
            if ((Sk - n) % 2 != 0) {
                k++;
                Sk = (1 + k) * k / 2;
            }
        }
        int i = (Sk - n) / 2;
        System.out.println("maximum number is : " + k + "the number with -ve sign is : " + i);
    }

solved obtain a number by addition or subtraction of consecutive natural numbers