数を形成するまで追加の連続した数字の全てのセットを取得する方法?

v_ag:

私は数を形成するまで追加の連続した数字のセットを生成するプログラムを作成したいです。例えば。入力された番号が15であれば、それは与えるべきです -

7, 8
4, 5, 6
1, 2, 3, 4, 5

収まるような何かを行うことができますいくつかの式/アルゴリズム/ループが。それは配列を生成したり、それを印刷できます。これは、数学の問題や愚かな質問を見えるかもしれませんが、私は実際にJavaでプログラム的にそれを行う方法を見つけ出すことはできません。

ことを行うことができ、正確なコードを与えることをしてみてください。

いいえ:

それは非常にきれいなアルゴリズムを伝えるように私は、MBOの答え@上で展開するでしょう。ウィキはあなたの便宜のために下にコピーされ、等差数列の良いイントロが用意されています。

和

導出

ここでは、画像の説明を入力します。

The sum of a sequence starting with number a and consisting of n consecutive numbers:

S = (n/2) * [2 * a + (n-1) * d]

For consecutive numbers the step d is 1.

S = (n/2) * [2 * a + (n-1)]

Here we can transition to @MBo's post.

P = 2 * S = n * [2 * a + (n-1)]

We can iterate all possible counts of consecutive numbers n and check if the resulting a is valid (i.e. a is an integer).

Let's factor out a.

Say P = n * q => q = 2 * a + (n-1) => 2 * a = q - n + 1 => a = (q - n + 1) / 2

Filters

1) we mentioned we could iterate all possible counts of consecutive numbers n, but given p = n * q it's safe to say n needs to be a divisor of p.

  • p % n == 0
  • nMax = (int)Math.sqrt(p)

2)a整数であり、a = (q - n + 1) / 2=>は(q - n + 1)さえ=>されるq - n奇数です。

  • ((q - n) & 1) == 1

実装

import java.util.*;
import java.lang.Math;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;

public class Progressions
{
    public static void main(String[] args)
    {
        List<List<Integer>> list = Calculate(15);
        System.out.print(list);
    }

    public static List<List<Integer>> Calculate(int s)
    {
        List<List<Integer>> list = new ArrayList<>();
        int p = 2*s;
        int nMax = (int)Math.sqrt(p);
        for (int n=2; n<=nMax; n++) {
            if(p % n == 0) {
                int q = p / n;
                if(((q - n) & 1) == 1) {          
                    int a = (q - n + 1) / 2;
                    list.add(range(a,n));
                }
            }
        }
        return list;
    }

    public static List<Integer> range(int a, int n) {
        return IntStream.range(a, a+n)
            .boxed()
            .collect(toList());
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=171357&siteId=1