UVA - 10025 The ? 1 ? 2 ? … ? n = k problem
题目大意:给一个数 让 ?1?2?3…..?n 等于这个数 ?可以是+ 或 - 求n的值
解题思路:先全部取正号,找到比给的数 n大的 一个 s (s = 1+ 2 +3 …) 然后 要取到这个数只要 在s中的一个数取负号 即可, 单s 中数取符号时 新得到的s 和 原来的s一定数相差 为偶数 例如 s = 1+ 2 +3 = 6 s2 = - 1 + 2+3 = 4; 所以 如果 s - n 不等于偶数就不能成立, 所以枚举找到最先为偶数的 即是 最少的
#include <cstdio>
#include <cmath>
using namespace std;
int main() {
int N;
scanf("%d", &N);
int f = 1;
while (N--) {
int M;
scanf("%d", &M);
int t = 0 ;
int s;
for (int i = 1; ; i++ ) {
s = i*(i+1)/2;
if ( s >= abs(M)) {
if ( (s - M)%2 != 0) continue;
t = i;
break;
}
}
if (f != 1) printf("\n");
f++;
printf("%d\n", t);
}
}