您的位置:首页 > 其它

UVALive6929 Sums

2018-02-20 01:19 393 查看
Given an integer N, express it as the sum of at least two consecutive positive integers. For example:• 10 = 1 + 2 + 3 + 4• 24 = 7 + 8 + 9If there are multiple solutions, output the one with the smallest possible number of summands.InputThe first line of input contains the number of test cases T. The descriptions of the test cases follow:    Each test case consists of one line containing an integer N (1 ≤ N ≤ 109).OutputFor each test case, output a single line containing the equation in the format:N = a + (a + 1) + ...+ bas in the example. If there is no solution, output a single word ‘IMPOSSIBLE’ instead.Sample Input381024Sample OutputIMPOSSIBLE10 = 1 + 2 + 3 + 424 = 7 + 8 + 9

问题链接:UVALive6929 Sums
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <float.h>
using namespace std;

int main()
{
int n;
scanf("%d",&n);
int a,m;
while(n--)
{
scanf("%d",&a);
if(a<=2)
printf("IMPOSSIBLE\n");
else if(a%2)
{
m=a/2;
printf("%d = %d + %d\n",a,m,m+1);
}
else
{// 2的k次方则不能表示为和
//            连续N个自然数的和为
//            S=n+(n+1)+(n+2)…+(n+m)=(2n+m)(m+1)/2
//            若m为奇数,则2n+m为奇数若m为偶数,
//            则m+1为奇数则N个自然数的和必为奇数*偶数或奇数*奇数
//            2^n无论怎么分分不出这样的奇数*偶数,所以不可能写成n个连续自然数的和
int t=a;
while(t%2==0)
t/=2;
if(t==1)
{
printf("IMPOSSIBLE\n");
continue;
}
// 等差数列和的通项公式Sk=ka1+k(k-1)d/2,这里d=1
// 那么a1=(Sk-k(k-1)/2)/k
// 用Sn(程序中的a),求a1和k,这里k>=3
int k;
for(k=3;;k++)
{
t=(a-k*(k-1)/2)/k;
if(k*t+k*(k-1)/2==a)
break;
}
printf("%d = %d", a, t);
for(int i=2; i<=k; i++)
printf(" + %d", ++t);
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: