1. Topic
Given a positive integer N and length L, find a continuous non-negative integer whose length is 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.
例如 N = 18 L = 2:
5 + 6 + 7 = 18
3 + 4 + 5 + 6 = 18
All meet the requirements, but we output shorter 5 6 7
Enter description:
The input data includes one line: two positive integers N (1 ≤ N ≤ 1000000000), L (2 ≤ L ≤ 100)
Output description:
Output this segment of consecutive non-negative integers from small to large, separated by spaces, and no spaces at the end of the line. If there is no such sequence or the length of the sequence found is greater than 100, output No
Example 1
input
18 2
Output
5 6 7
Two, solve
Ideas:
Arithmetic formula: S = a 1 n + n (n − 1) d 2 S = a_1n + \frac{n(n-1)d}{2}S=a1n+2n(n−1)d
Set S = N, n = L, d = 1 S=N, n = L, d = 1S=N,n=L,d=1 Substituting the above formula, we get:
a 1 = 2 N - L 2 + L 2 L a_1 = \ frac {2N - L ^ 2 + L} {2L} a1=2 L2 N−L2+L
Code:
import java.util.Scanner;
public class Main {
public static int display(int N,int L) {
for(int i=L;i<101;i++) {
if ( (2*N-i*(i-1))%(2*i)==0 )
if ((2*N-i*(i-1))/(2*i)>=0) {
int a1=(2*N-i*(i-1))/(2*i);
for(int j=0;j<i-1;j++) {
System.out.print(a1+j+" ");
}
System.out.print(a1+(i-1));
return 0;
}
}
System.out.print("No");
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console=new Scanner(System.in);
int N=console.nextInt();
int L=console.nextInt();
display(N,L);
}
}
Time complexity: O (L) O (L)O ( L )
space complexity:O (1) O(1)O ( 1 )