我在这里发布的程序是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/