A positive integer is represented as the sum of n consecutive positive integers (1th session 2nd)

Source: Internet
Author: User

Topic Requirements

Problem Description : A positive integer may be represented as a sum of N (n>=2) consecutive positive integers, such as:

15=1+2+3+4+5

15=4+5+6

15=7+8

Write a program that finds all consecutive positive integer sequences that meet this requirement, based on any positive integer entered.

Sample Input :

Sample Output : 1+2+3+4+5

4+5+6

7+8

Solution Solutions

Test instructions very understood, the first intuition of this problem is triple-cycle violence, the first control sequence starting point, the second control sequence element number, the third output conforms to the sequence of test instructions, but obviously, this is very time-consuming, can improve? OK!

Because it is a sequential sequence, consider using the arithmetic progression property.

For a linear sequence, there are three key variables: one is tolerance, one is the starting point of the sequence, and the other is the sequence length. Obviously this sequence tolerance is 1, then only the sequence start and sequence length nare considered. Aftertaste arithmetic progression summation formula:


The following information can be obtained from the above formula:

1. The upper type is slightly deformed, 2s-(n-1) N=2a*n, namely 2s> (n-1) n>0.

2. Also 2s= (2a+n-1) n, therefore: 2s%n==0, (2s/n-n+1)%2==0.

3.a= (2s/n-n+1)/2

Therefore, we can consider the method of controlling the length of the sequence to directly find a sequence starting point conforming to test instructions, and then output.

Source code Example

results show

Summary

Although the topic is simple, but still need to consider, do not get a triple loop ...

A positive integer is represented as the sum of n consecutive positive integers (1th session 2nd)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.