Continuous sequence is s

Source: Internet
Author: User

Question: enter an integer s to print all consecutive integer sequences (containing at least two numbers) for s ). For example, if input 9 is used, two sequences (2, 3, 4, 4, and 5) are output.


Solution 1: because a sequence requires at least two numbers, the upper limit of the two numbers is (1 + s)/2. We can enumerate the starting and ending points of the sequence to find all the satisfied sequences. The time complexity is O (n ^ 2), which is relatively low.

Solution 2: we set two pointers, start and end, to indicate the start and end of the Current sequence respectively, and remember the sum of the sequence and sum. When sum = s, this sequence is output, and end moves one bit backward. If sum> s, start moves one bit backward. If sum <s, then the end will move one digit backwards.

Until start <(1 + s)/2 ends the cycle, time complexity O (n), High Efficiency


# Include
 
  
# Include
  
   
# Include
   
    
# Define deusing namespace std; // print the sequence void PrintNum (int start, int end) {for (int I = start; I <= end; I ++) {printf ("% d", I) ;}printf ("\ n") ;}// locate the sum of the two numbers and svoid FindSequenceSum (int s) {if (s <3) {// return;} int start = 1; int end = 2; int sum = 3; int mid = (1 + s)> 1; // cyclically locate all the while (start <mid) {// the starting point of the sequence must be less than half of (1 + s) if (sum = s) {// print PrintNum (start, end); end ++; sum + = end;} else if (sum> s) directly for the sum sequence) {// and the sequence greater than s move a sum-= start; start ++;} from the start point ;} else {// and the sequence smaller than s move one end ++; sum + = end ;}} int main () {FindSequenceSum (9 ); getchar (); return 0 ;}
   
  
 


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.