题面:
King George has recently decided that he would like to have a new design for the royal graveyard. The graveyard must consist of several sections, each of which must be a square of graves. All sections must have different number of graves.
After a consultation with his astrologer, King George decided that the lengths of section sides must be a sequence of successive positive integer numbers. A section with side length s contains s 2 graves. George has estimated the total number of graves that will be located on the graveyard and now wants to know all possible graveyard designs satisfying the condition. You were asked to find them.
输入:
Input file contains n — the number of graves to be located in the graveyard (1 <= n <= 10 14 )
输出:
On the first line of the output file print k — the number of possible graveyard designs. Next k lines must contain the descriptions of the graveyards. Each line must start with l — the number of sections in the corresponding graveyard, followed by l integers — the lengths of section sides (successive positive integer numbers). Output line’s in descending order of l.
题目翻译:
给定一个数字n(1<=n<=1014),找到连续的整数a1,a2…aX,使得a12 + a22+…+aX2 = n.
输入:
一个数字n
输出:
第一行为k,代表符合条件的连续整数有多少组.之后k行包括一个数l,代表这一组整数的个数,之后为l个数字.
题目分析:
既然是要找连续整数,所以我们用两个变量start,end来表示这段连续整数的第一个数和最后一个数.
从start = 1, end = 1开始.
用sum来表示start和end之间所有数的平方和
当sum小于n时,end自增1.
当sum大于n时,start自减1.
当sun等于n时,记录下此时的start和end,end自增1.
重复以上操作,直到end^2>n
最后输出答案的个数k(每次sum=n时,k自增1).
然后输出前面记录下来的每一段符合条件的整数.
代码:
//因为要先输出答案的个数k,再输出答案,所以这里要先把答案存起来.
//因为不知道答案会有多少组,所以用链表.
#include<stdio.h>
struct answer{
long long l;
long long start;
long long end;
struct answer *next;
};//用来记录答案
int main(){
long long n, sum, l, start, end, count, i;
struct answer *head = 0;
struct answer *p = 0;
scanf("%lld", &n);
sum = 0;count = 0;start = 1;end = 1;l = 2;
while(end < sqrt(n)+1){
sum+= end*end;
end++;
while(sum < n){
sum += end*end;
end++;
}
while(sum > n){
sum -= start*start;
start++;
}
l = end - start;
if(sum == n){
count++;
if(!head){
head = (struct answer*)malloc(sizeof(struct answer));
head->l = l;
head->start = start;
head->end = end;
head->next = 0;
p = head;
}else{
p->next = (struct answer*)malloc(sizeof(struct answer));
p = p->next;
p->l = l;
p->start = start;
p->end = end;
p->next = 0;
}
}
}
printf("%lld\n", count);
while(head){
printf("%lld ", head->l);
for(i = head->start; i < head->end; i++){
printf("%lld%c", i, ((i == head->end-1)?'\n':' '));
}
head = head->next;
}//输出所有符合条件的整数段
}