题目链接:https://csacademy.com/contest/archive/task/consecutive-sum
题目大意:给出一个数n,判断它是否能够被至少两个的连续整数和表示出来。能的话输出A到B,A+A+1+……+B = n,否则输出-1。
解题思路:使用双指针,从前到后计算前i个数的和,如果这个数超过n,就从j=1开始减去j,如果减法过程中当前和等于n,直接退出,如果小于,继续向前将下一个数加入当前和中继续判断。
代码:
1 const int maxn = 1e6 + 5; 2 int n; 3 4 void solve(){ 5 int i = 1, j = 1; 6 ll tmp = 0; 7 for(i; i <= n; i++){ 8 tmp += i; 9 if(tmp < n) continue; 10 else if(tmp == n) break; 11 else{ 12 while(tmp > n){ 13 tmp -= j; 14 j++; 15 } 16 if(tmp == n) break; 17 } 18 } 19 if(j < i && tmp == n) printf("%d %d ", j, i); 20 else puts("-1"); 21 return; 22 } 23 int main(){ 24 scanf("%d", &n); 25 solve(); 26 }
题目:
Consecutive Sum
Time limit: 1000 ms
Memory limit: 256 MB
Memory limit: 256 MB
You are given a number NN. Write NN as a sum of at least 22 positive consecutive integers.
Standard input
The first line contains a single integer NN.
Standard output
Print two integers AA and BB, representing the smallest and the largest terms. Basically, NN should be equal to A + (A + 1) + ... + BA+(A+1)+...+B. If there are multiple solutions you can output any of them.
Constraints and notes
- 1 leq N leq 10^51≤N≤105
- 1 leq A < B1≤A<B
Input | Output | Explanation |
---|---|---|
7 |
3 4 |
3+4=73+4=7 |
15 |
1 5 |
1+2+3+4+5=151+2+3+4+5=15 |
4 |
-1 |