Sequence and problem solving method C++

 

Title description:

 

Given a positive integer N and length L, find a continuous non-negative integer with a length greater than or equal to L, and their sum is exactly N. There may be multiple answers, we need to find the one with the smallest length.
For example, N = 18 L = 2:
5 + 6 + 7 = 18
3 + 4 + 5 + 6 = 18
are all satisfactory, but we output a shorter 5 6 7

Enter description:

输入数据包括一行: 两个正整数N(1 ≤ N ≤ 1000000000),L(2 ≤ L ≤ 100)

Output description:

从小到大输出这段连续非负整数,以空格分隔,行末无空格。如果没有这样的序列或者找出的序列长度大于100,则输出No

Example 1

enter

copy

18 2

Output

copy

5 6 7

 

Analysis, this is an arithmetic sequence, just find the first number of the arithmetic sequence, n is from small to large, the first one found is the smallest one.

 

C++ solution:

#include<iostream>
using namespace std;

int main(){
    int i,n,N,L;
    cin>>N>>L;
    for(n=L;n<=100;n++){
            if((2*N-n*n+n)%(2*n) == 0){
                int start=(2*N-n*n+n)/(2*n);
                for(i=0;i<n-1;i++)
                    cout<<start+i<<" ";
                cout<<start+n-1;
                return 0;
            }
        }
    cout<<"No";
}

Why did I write:

for(i=0;i<n-1;i++)
   cout<<start+i<<" ";
cout<<start+n-1;

Written as:

for(i=0;i<=n-1;i++)
    cout<<start+i<<" ";
    

Can't it?

 

No, so the last number will have a space with "". It is judged as abnormal in its compiler, and the following prompt:

 

Guess you like

Origin blog.csdn.net/sinat_39416814/article/details/105101662