您的位置:首页 > 其它

UVA 10025(数学)

2014-05-08 23:57 351 查看


 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 obtain k = 12 , the expression to be used will be:
- 1 + 2 + 3 + 4 + 5 + 6 - 7 = 12

with n = 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 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

12

-3646397



Sample Output

7

2701


先求出第一s=1+2+3+...+n>=k的第一个n,如果s-k为偶数那么此时n,就是最小值,否则最小值为n+1或n+2(因为连续的两个数里一定有一个奇数,就能改变s-k的奇偶性了);因为
 首先n个数的和要和k奇偶性相同,因为不管怎么改变符号n个数的奇偶性不会变,奇偶性相同那么n-k就一定是偶数,n-k是偶数那么变号的数就应该是(n-k)/2,因为s》=k,s-(s-k)=1+2+...-(n-k)/2+....n=k;所以此时求出来的n一定可以构造出k,且为最小的,代码如下

#include<stdio.h>
#include<math.h>
int main()
{
int i,k,n,m;
scanf("%d",&n);
while(n--)
{
scanf("%d",&k);
if(m==0)printf("3\n");
else
{
k=k>0?k:-k;
m=sqrt(2*k);
for(i=m;i*(i+1)<2*k;i++);
while(1)
if((i*(i+1)/2-k)%2)i++;//实际上两次之内就可以改奇偶性了
else break;
printf("%d\n",i);
}
if(n)printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva 数学