POJ 1844 Sum(数学)

1726 ワード

テーマリンク:Click me!
                                                         Sum
Consider the natural numbers from 1 to N. By associating to each number a sign (+ or -) and calculating the value of this expression we obtain a sum S. The problem is to determine for a given sum S the minimum number N for which we can obtain S by associating signs for all numbers between 1 to N.Description
For a given S, find out the minimum value N in order to obtain S according to the conditions of the problem.
Input
The only line contains in the first line a positive integer S (0< S <= 100000) which represents the sum to be obtained.
Output
The output will contain the minimum number N for which the sum S can be obtained.
Sample Input
12

Sample Output
7

Hint
The sum 12 can be obtained from at least 7 terms in the following way: 12 = -1+2+3+4+5+6-7.
問題の解析:
この問題は、Sを与えるには、最小のNを探す必要があります.そして、1~Nの和(正負可能)からSを出力する必要があります.このNを出力すればいいです.例えば、12=-1+2+3+4+5+6-7で、結果は7です.
実は2行のコードについて、第一に、最小のN、つまり同じようにSを得ることができる場合、記号のほとんどが正であれば、できるだけ最小のNを得ることができる.例えば、12=-1+2+3+4+5+6-7、12=-1+2+3-4+5+6-7+8である.そして(SUM−S)%2=0であれば,このSは長く得られ,得られたNは最小のNであった.
コード編:
#include 
#include 
#include 
#include 
using namespace std;
int main()
{
    int sum, i, j, k;
    scanf("%d",&k);
    sum = 0;
    i = 1;
    while(1)
    {
        sum += i++;
        if(sum >= k && (sum - k) % 2 == 0)
        {
            printf("%d
",i - 1); return 0; } } return 0; }

 
OVER!