HDU 2058 The sum problem

Source: Internet
Author: User

The sum problem
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission (s): 12104 Accepted Submission (s): 3666

 


Problem Description
Given a sequence 1, 2, 3,... N, your job is to calculate all the possible sub-sequences that the sum of the sub-sequence is M.


Input
Input contains multiple test cases. each case contains two integers N, M (1 <= N, M <= 1000000000). input ends with N = M = 0.

 

Output
For each test case, print all the possible sub-sequence that its sum is M. The format is show in the sample below. print a blank line after each test case.

 

Sample Input
20 10
50 30
0 0

Sample Output
[1, 4]
[10, 10]

[4, 8]
[6, 9]
[9, 11]
[30, 30]
Summary:

Observe a + 1, a + 2... A + d
Add all equal to M
That is, (a + 1 + a + d) * d/2 = M,
Here d is the square. We can start with the length d so that we can convert the range from M to M ^ 1/2;


Here we will explain ① and ② In the Code:
①: When a + 1, a + 2... When the sum of a + 3 is M, that is
(A + 1 + a + d) * d/2 = M
The minimum a value is 0, so (d + 1) * d/2 = M, d goes to the maximum value, which reduces the time complexity in this step.
D is sqrt (2 * M)

② :( A + 1 + a + d) * d/2 = M
So a * d + (d + 1)/2 = M
Therefore, to establish the equation, M-(d + 1)/2 must be a multiple of d.


 

 

import java.util.*;import java.io.*;import java.math.BigInteger;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));while(sc.hasNextInt()){ int n=sc.nextInt();int m=sc.nextInt();if(n==0&&m==0)System.exit(0);int t1=(int)Math.sqrt(2*m);for(int i=t1;i>=1;i--){long temp=m-(i*i+i)/2;if(temp%i==0)System.out.println("["+(temp/i+1)+","+(temp/i+i)+"]");}System.out.println();}}}

 

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.