2016-07-22 48 views
-3

當n等於50時,此函數返回一個負數,是否有替代LongStream的「BigIntegerStream」,允許「n」變大?LongStream Java rangeClosed reduce - 如何避免負面回報?

public static long factorial(int n) { 

    if (n > 50 || n < 0) 
     throw new IllegalArgumentException(n + " is out of range"); 

    return LongStream.rangeClosed(2, n).reduce(1, (a, b) -> a * b); 

} 
+3

是的。 '流'。 – Tunaki

回答

1

你其實並不需要一個更大的原始容量,相反,你可能需要使用一個Stream<BigInteger>像由@Tunaki說,但保持原有IntStream

以下代碼完美工作。

public static void main(String[] args) { 
    System.out.println(factorial(10)); // 3 628 800 => CORRECT 
} 

public static BigInteger factorial(int n) { 
    return IntStream.rangeClosed(2, n) 
        .mapToObj(BigInteger::valueOf) 
        .reduce(BigInteger.ONE, (a, b) -> a.multiply(b)); 
} 
+0

我會試一試,去找你的方法,但是有一個嚴重的問題,我製作的解決方案是將高值賦給具有約束限制大小的數組索引:Integer.MAX_VALUE 問題出現在階乘輸入得到高於20,我的代碼甚至需要支持一個階乘(5,000) - 五千...我想我得到f * ck * d與我的這個算法... [堆挑戰](https: //www.hackerrank.com/challenges/minimum-average-waiting-time/submissions/code/24209486) – KRonaldoK

+0

@KRonaldoK由於在使用BigInteger(http:// stackoverflow)時存在內存限制,因此支持factorial 5000非常困難。 COM /問題/ 2163434 /不-的BigInteger-不斷溢出) –