码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 10025(数学)

时间:2014-05-09 06:10:40      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:uva   数学   

 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 10025(数学),布布扣,bubuko.com

UVA 10025(数学)

标签:uva   数学   

原文地址:http://blog.csdn.net/acvcla/article/details/25345533

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!