0

The program I have posted here is problem of marbles from spoj, and I know it has been discussed here, and I know the logic.

But when I am calculating the factorial, it overflows even on calculation of 29 factorial. What can I do?

long long is not supported

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();


    }

}
Pang
  • 9,564
  • 146
  • 81
  • 122
Jstorm99
  • 13
  • 7

2 Answers2

2

We should use BigInteger to calculate factorials of large numbers.

But you might use lots of JVM memory.

Example:

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;
    }
}

Check out this live demo

Community
  • 1
  • 1
rhitz
  • 1,892
  • 2
  • 21
  • 26
  • Short and nice answer (**`+1`**) – Shrinivas Shukla Aug 01 '15 at 10:32
  • yes i have checked your demo ,its working fine (thanks),but can you tell me why 'double' data type returns **1.21645100408832E17** _(factorial of 20)_ Even though i have initialized variable as follows: double result=1; and not double=1.0; – Jstorm99 Aug 02 '15 at 17:54
  • well, First your answer refers to factorial of 19, please check your code for error/logical error or post it here. Second: 1.21645100408832E17 is in the e notation. Many computer programs/calculators present very large and very small results in scientific e notation. For example aEb is equivalent to a*10^b. check : https://en.wikipedia.org/wiki/Scientific_notation. Hope this solve your doubt. Please accept the answer, as it help everyone who visits this question in future. – rhitz Aug 02 '15 at 18:09
0

It seems to me that double should work and give you a good approximation of the value but you could use BigInteger from java.math for arbitrary precision math so you always get the precise number.

FrankM
  • 772
  • 7
  • 11