The? 1? 2? ...? N = K Problem |
The Problem
Given the following formula, one can set operators '+' or '-' instead of each '? ', In order to obtain a given K
? 1? 2? ...? N = K
For example: To obtainK = 12, The expression to be used will be:
-1 + 2 + 3 + 4 + 5 + 6-7 = 12
WithN = 7
The input
The first line is the number of test cases, followed by a blank line.
Each test case of the input contains integer K (0 <=| K |<= 1000000000 ).
Each test case will be separated by a single line.
The output
For each test case, your program shocould print the minimal possible N (1 <= N) to obtain K with the above formula.
Print a blank line between the outputs for two consecutive test cases.
Sample Input
212-3646397
Sample output
72701
At first glance, I don't have any ideas. I 'd like to try it out.
Num maxsum
1 1
2 3
3 6
4 10
5 15
6 21
7 28
12 <15 because it should be 5 digits, but it is 7
Therefore, the problem is found: Can a number n be expressed using M numbers? The condition is that all M numbers are greater than N, and all numbers are obtained +;
If the sum of all values is greater than N, the second condition must be met: m numbers and N must be an even number. Take 12 as an example. The sum of the five numbers is 15. To program 12, the value must be-3, since it was previously +, we must change some numbers -,
+ X is changed to-X, with 2x less. Therefore, only the even number is reduced. Therefore, if five cannot be six, 21 cannot be used. Therefore, 7 is used. Then, a negative number is equivalent to a positive or negative number,
0 is special 1-2 + 3;
The rule is found many times wrong because of the precision of the real number;
M * (m + 1)/2 = N
M = (-1 + SQRT (1 + 4*2n)/2 wrong several times, it is estimated that due to the loss of precision, m of several numbers is calculated to be greater than the actual accuracy ratio.
The method is to make the calculated value slightly smaller than the actual m value;
Can M = SQRT (2 * n); ignore m + 1 as m; or calculate M minus a small constant, I am-10, of course, a value smaller than 0 after-10 must be assigned again.
# Include <stdio. h>
# Include <math. h>
Void main ()
{Int m, n, t, s;
Scanf ("% d", & T );
While (t --)
{Scanf ("% d", & N );
If (n = 0) M = 3;
Else
{
If (n <0) n =-N;
M = (-1 + SQRT (1 + 8 * n)/2-10;
If (M <1) M = 1;
S = m * (m + 1)/2;
While (S <n) | (S-N) % 2 = 1 ))
{++ M; S = m * (m + 1)/2 ;}
}
Printf ("% d \ n", M );
If (t) printf ("\ n ");
}
}