首页 技术 正文
技术 2022年11月16日
0 收藏 717 点赞 2,413 浏览 970 个字
 The ? 1 ? 2 ? … ? n = k problem 

Theproblem

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

TheInput

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

212-3646397

Sample Output

72701

题意不累赘~

做法:

假设sum1 = a1 + a2 + a3 + … + an + x >= k

而sum2 = a1 + a2 + a3 + … + an – x = k

那么sum1 – sum2 = 2x

也就是说, 无论k的正负, 全把k当正数处理, 一直累加正数得到sum1 与 不按全当正数处理得到的sum2 相差的值是一个偶数(2x, 即负数的绝对值的两倍~)

故, 全部从1累加到n吧, 直到 (sum >= k && (sum – k) % 2 == 0)

AC代码:

#include<stdio.h>int T;int main() {
scanf("%d", &T);
while(T--) {
int k;
int sum = 0;
scanf("%d", &k);
if(k < 0)
k = (-1 * k);
for(int i = 1; ;i++) {
sum += i;
if(sum >= k && (sum-k) % 2 == 0) {
printf("%d\n", i);
break;
}
}
if(T)
printf("\n");
}
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,958
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,482
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,328
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,111
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,743
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,777