java - 在计算阶乘时,即使使用 long 和 double,我也会得到垃圾值

标签 java long-integer

我在这里发布的程序是marbles from spoj的问题, 和我 我知道这里已经讨论过了,我也知道其中的逻辑。

但是当我计算阶乘时,即使计算 29 阶乘也会溢出。我能做什么?

不支持long long

package marbles_spoj;

import java.util.Scanner;

public class combinations_with_repetition {

    public static long calc(long n,long k)
    {   
        System.out.println(n+"  "+k);
        long res=0;
        res=factorial(n)/(factorial(k)*factorial(n-k)); 
        return res;
    }

    static long factorial(long n)
    {   long result=1;
        if (n==1||n==0)return 1;
        else 
            for(long i=2;i<n;i++)result=result*i;
    //System.out.println("result is :"+result);
        return result;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Scanner sc = new Scanner(System.in);

        System.out.println("Enter no. of marbles to b picked up");
        long n=sc.nextLong();
        System.out.println("enter no. of colors of marbles availables");
        long r=sc.nextLong();

        System.out.println("Number of combinations possible "+calc(n-1,r-1));
        sc.close();


    }

}

最佳答案

我们应该使用BigInteger计算factorials of large numbers

但是您可能会使用大量 JVM 内存。

示例:

public class FactorialUtil
{
    public static BigInteger factorial(int n)
    {
        BigInteger ret = BigInteger.ONE;
        for (int i = 1; i <= n; ++i) ret = ret.multiply(BigInteger.valueOf(i));
        return ret;
    }
}

看看这个 live demo

关于java - 在计算阶乘时,即使使用 long 和 double,我也会得到垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31760637/

相关文章:

c++ - 有什么方法可以设置 8 字节 (x64) 的 C++ 长类型大小?

c# - 我可以用什么来代替可克隆的 "long"?

java - 为什么我的代码显示错误 - 'integer number too large' ;尽管我已经将参数类型声明为 long?

java - 用玩! GAE 上的缓存

Java - shift int 枚举

java - 替换字符串中的值

c# - 随机排序的长序列

c++ - 从 long long 中减去 int

java - Gson解码json

java - 将 setText 设置为 EditText 时出现 NullPointerException - onDateSet