C++ beginner's output is a series of positive integers that can be represented based on any positive integer input

  • 2020-05-09 18:52:18
  • OfStack

It is possible that a positive integer can be represented as n( > =2) sum of consecutive positive integers, such as:

15=1+2+3+4+5
15=4+5+6
15=7+8

Write a program that finds a sequence of all consecutive positive integers that meet this requirement, based on any one of the positive integers entered.

Input data: 1 positive integer, provided to the program as a command-line argument.

Output data: print out a sequence of all positive integers matching the description on standard output, 1 sequence per line. Each sequence starts with the smallest positive integer of the sequence and is printed in the order from small to large. If the result has multiple sequences, print each sequence from small to large according to the size of the smallest positive integer in each sequence. In addition, sequences are not allowed to be repeated, and the integers in the sequence are separated by 1 space. If there is no matching sequence, output "NONE".

For example, for 15, the output is:

1 2 3 4 5
4 5 6
7 8

For 16, the output is:

NONE

This is a baidu star programming contest in 2005 preliminary questions. The idea is as follows:

1. The number that meets the requirement is continuous, so as long as the starting value is selected, the sum can be added;

2. Be sure to iterate through all possible starting values and keep the loop to a minimum. You can see from analysis 1 that a number is at least a sum of two Numbers, and that's because these two Numbers are continuous. So the maximum starting value is no more than 1/2 of that.

The code is VC6.0 to verify OK. Please clap brick, ^_^


#include <iostream>
#include <vector>
using namespace std;
//  According to any input 1 A sequence of positive integers that may be represented 
void Numbers(int number)
{
if (number <= )
{
return;
}
vector<int> save;
bool exist = false;
//  Walk through the possible starting values 
for (int possible = ; possible < number / + ; possible++)
{
int start = possible;
int i = start;
int sum = ;
while (sum <= number) //  Saves consecutive positive integers that can be represented and outputs them 
{
sum += start;
if (sum == number)
{
exist = true;
for (; i < start + ; i++)
{
save.push_back(i);
}
for (i = ; i < save.size(); i++)
{
cout << save[i] << " ";
}
save.clear(); //  Empty and save 1 Possible sequence 
cout << endl;
}
start++;
}
}
if (false == exist)
{
cout << "NONE" << endl;
}
}
int main(int argc, char **argv)
{
const int number = ;
Numbers(number);
Numbers();
return ;
}

The above is this site to introduce you to C++ beginners according to the input of any 1 positive integer, the output may be expressed as a continuous positive integer, hope to help you!


Related articles: