10025-the? 1? 2? ... ? n = k problem
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=99&page=show_problem &problem=966
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 obtain k = expression to is used would be: -1 + 2 + 3 + 4 + 5 + 6-7 =/ with n = 7
The Input
The 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 is separated by a.
The Output
For each test case, your program should 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
2
-3646397
Sample Output
7
2701
First of all, 1~n and sum must be >=k. When the sum is >n to subtract a number, such as adding a-number to the front of number a, which is equivalent to Sum-2 * A, which means that each drop can only be even, then a sum of 2 = k 2 is required. (negative numbers in the same vein)
O (√k) code:
/*0.006s*/
#include <cstdio>
#include <algorithm>
using namespace std;
int main (void)
{
int T, k, sum, I;
BOOL flag = FALSE;
scanf ("%d", &t);
while (t--)
{
if (flag)
Putchar (' \ n ');
else
flag = true;
scanf ("%d", &k);
K = ABS (k), sum = 0;
for (i = 1;; i++)
{
sum = i;
if (sum >= k && ((sum-k) & 1) = = 0)
{
printf ("%d\n", I);
break;
}
}} return 0;
}