簡體   English   中英

使用 Java 8 IntStream 計算階乘?

[英]calculating factorial using Java 8 IntStream?

我在 Java 8 和 lambda 表達式以及Stream中相對較新,我可以使用for循環或遞歸計算階乘。 但是有沒有辦法使用IntStream來計算一個數字的階乘? 即使在整數范圍內使用階乘我也很好。

我在這里閱讀了IntStream文檔, http: //docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html,我可以看到很多方法,但不確定我可以使用哪一個計算階乘。

例如,有rang方法說,

range(int startInclusive, int endExclusive) 以增量 1 返回從 startInclusive(包含)到 endExclusive(不包含)的順序有序 IntStream。

所以我可以用它來為 IntStream 提供要相乘以計算階乘的數字范圍。

number = 5;
IntStream.range(1, number)

但是如何將這些數字相乘以獲得階乘?

您可以將IntStream::reduce用於此作業,

int number = 5;
IntStream.rangeClosed(2, number).reduce(1, (x, y) -> x * y)

要獲得所有無限階乘的流,您可以執行以下操作:

class Pair{
   final int num;
   final int value;

    Pair(int num, int value) {
        this.num = num;
        this.value = value;
    }

}

Stream<Pair> allFactorials = Stream.iterate(new Pair(1,1), 
                                   x -> new Pair(x.num+1, x.value * (x.num+1)));

allFactorials是從 1 到 ..... 的數字階乘流 要獲得 1 到 10 的階乘:

allFactorials.limit(10).forEach(x -> System.out.print(x.value+", "));

它打印:1、2、6、24、120、720、5040、40320、362880、3628800、

現在說你只希望有一個特定數字的階乘然后做:

allFactorials.limit(number).reduce((previous, current) -> current).get()

最好的部分是您不會再次為新數字重新計算,而是建立在歷史的基礎上。

使用 LongStream.range() 您可以計算小於 20 的階乘。如果您需要計算更大的數字,請使用 BigInteger 創建流:

 public BigInteger factorial(int number) {
    if (number < 20) {
        return BigInteger.valueOf(
                LongStream.range(1, number + 1).reduce((previous, current) -> previous * current).getAsLong()
        );
    } else {
        BigInteger result = factorial(19);
        return result.multiply(Stream.iterate(BigInteger.valueOf(20), i -> i.add(BigInteger.ONE)).limit(number - 19)
                .reduce((previous, current) -> previous.multiply(current)).get()
        );
    }
}

我們可以像這樣用 AtomicInteger 解決這個問題:

  int num = 5;
  AtomicInteger sum = new AtomicInteger(1);
  IntStream.rangeClosed(2, num).forEach(i -> {
    sum.updateAndGet(v -> v * i);
        if (i == num) {
          System.out.println(sum.get());
        }
  });

我認為我們可以將主要條件更改為: 1,v v-1,s t 使用函數 reduce。 也許我們可以在執行主要規則之前進行過濾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM