UVa 10025 the? 1? 2? ... ? n = k problem: Math & Idea question & constant algorithm

Source: Internet
Author: User
Tags constant time limit

10025-the? 1? 2? ... ? n = k problem

Time limit:3.000 seconds

Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=99&page=show_problem &problem=966

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 = expression to is used would be: -1 + 2 + 3 + 4 + 5 + 6-7 =/ with n = 7

The Input

The 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 is separated by a.

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

-3646397

Sample Output

7

2701

First of all, 1~n and sum must be >=k. When the sum is >n to subtract a number, such as adding a-number to the front of number a, which is equivalent to Sum-2 * A, which means that each drop can only be even, then a sum of 2 = k 2 is required. (negative numbers in the same vein)

O (√k) code:

/*0.006s*/
  
#include <cstdio>
#include <algorithm>
using namespace std;
  
int main (void)
{
    int T, k, sum, I;
    BOOL flag = FALSE;
    scanf ("%d", &t);
    while (t--)
    {
        if (flag)
            Putchar (' \ n ');
        else
            flag = true;
        scanf ("%d", &k);
        K = ABS (k), sum = 0;
        for (i = 1;; i++)
        {
            sum = i;
            if (sum >= k && ((sum-k) & 1) = = 0)
            {
                printf ("%d\n", I);
                break;
            }
    }} return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.