Posted on

Description

题目描述

给出一个正整数N和长度L,找出一段长度大于等于L的连续非负整数,他们的和恰好为N。答案可能有多个,我我们需要找出长度最小的那个。
例如 N = 18 L = 2:
5 + 6 + 7 = 18
3 + 4 + 5 + 6 = 18
都是满足要求的,但是我们输出更短的 5 6 7

输入描述:

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

输出描述:

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

示例1

输入

18 2

输出

5 6 7

Submission

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner inStream = new Scanner(System.in);

        int N = inStream.nextInt();
        int L = inStream.nextInt();

        int firstNumber = -1;
        int l = 0;
        int i;

        for(i = L; i <= 100; i++) {
            // if L, N pair is possible
            if((N * 2) % i == 0) {
                int mid = N / i;

                // i is even
                if(i % 2 == 0) {
                    if((mid + mid + 1) * i / 2 == N) {
                        firstNumber = mid - i / 2 + 1;
                        l = i;
                        break;
                    }
                } else {
                    if(mid * i == N) {
                        firstNumber = mid - i / 2;
                        l = i;
                        break;
                    }
                }
            }
        }

        if(l == 0) {
            System.out.print("No");
        } else {
            for(i = 0; i < l; i++) {
                System.out.print(firstNumber + i);
                if(i != l - 1) {
                    System.out.print(" ");
                }
            }
        }

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *