程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 10025(數學)

UVA 10025(數學)

編輯:C++入門知識

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
#include
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;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved