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

UVA 10025(数学)

时间:2014-10-29 23:44:00      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   for   sp   

 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(数学)

标签:style   blog   http   io   color   os   ar   for   sp   

原文地址:http://www.cnblogs.com/gcczhongduan/p/4060555.html

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