10025 - The ? 1 ? 2 ? ... ? n = k problem 简单数论

 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

Alex Gevak
September 15, 2000 (Revised 4-10-00, Antonio Sanchez)
/*
 * Author:  
 * Created Time:  2013/10/15 16:03:09
 * File Name: C.cpp
 * solve: C.cpp
 */
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<string>
#include<map>
#include<stack>
#include<set>
#include<iostream>
#include<vector>
#include<queue>
//ios_base::sync_with_stdio(false);
//#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;
#define sz(v) ((int)(v).size())
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define repf(i, a, b) for (int i = (a); i <= (b); ++i)
#define repd(i, a, b) for (int i = (a); i >= (b); --i)
#define clr(x) memset(x,0,sizeof(x))
#define clrs( x , y ) memset(x,y,sizeof(x))
#define out(x) printf(#x" %d\n", x)
#define sqr(x) ((x) * (x))
typedef long long LL;

const int INF = 1000000000;
const double eps = 1e-8;
const int maxn = 30000;

int sgn(const double &x) {  return (x > eps) - (x < -eps); }

int main() 
{
    //freopen("in.txt","r",stdin);
    int T;
    cin>>T;
    int f = 0;
    while(T--)
    {
        if(f)
            cout<<endl;
        f = 1;
        LL n;
        cin>>n;
        if(n<0)
            n = -n;
        if(n == 0)
        {
            cout<<3<<endl;
            continue;
        }
        double temp = (sqrt(8*n + 1) - 1)/2.0;
        int ans = ceil(temp);
        
        int sum = (ans + 1)*ans/2;
        int gap = sum - n;
        int ans1;
        if(gap%2 == 0)
        {
            ans1 = ans;
        }else
        {
            for(int i = ans;;++i)
            {
                int tmp = i*(i+1)/2;
                gap = tmp - n;
                if(gap%2 == 0)
                {
                    ans1 = i;
                    break;
                }
            }
        }
        
        cout<<ans1<<endl;
        
    }
    return 0;
}

 

posted on 2013-10-15 20:53  keep trying  阅读(209)  评论(0编辑  收藏  举报

导航