例如輸入15,由於1+2+3+4+5=4+5+6=7+8=15,所以輸出3個連續序列1-5、4-6和7-8。
void CotinuousSeq(int n)
initialize a sequence
for i <- 1 to (1+n)/2
push first element
for j <- i+1 to (1+n)/2
if j+sum(tvec) <= n
then push into sequence
if sum(ivec) = n
then print the sequence and clear the sequence
else clear the sequence
C++實現
void CotinuousSeq(int n)
{
//initialize a sequence
vector<int> tvec;
//for i <- 1 to (1+n)/2
for(int i = 1; i <= (1+n)/2; ++i)
{
//push first element
tvec.push_back(i);
//for j <- i+1 to (1+n)/2
for(int j = i+1; j <= (1+n)/2; ++j)
{
//if j+sum(tvec) <= n
if((j + sum(tvec)) <= n)
{
//then push into sequence
tvec.push_back(j);
//if sum(ivec) = n
if(sum(tvec) == n)
{
//then print the sequence and clear the sequence
print(tvec);
tvec.clear();
break;
}
}
else
{
//else clear the sequence
tvec.clear();
break;
}
}
}
}