-5
import java.util.Scanner;

public class MathsHacker {

public static int fact(int n)
{
    if(n==0)
        return 1;
    else
        return n*fact(n-1);
}
/*
    I checked for 1 test case giving an input=5277
    it results in exception :
    Exception in thread "main" java.lang.ArithmeticException: / by zero
*/

public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);
    int T =in.nextInt();
    for(int a0 = 0; a0 < T; a0++)
    {
        int N = in.nextInt();
        if(N==1)
        {
            System.out.println("0");  
        }
        else
        {
            int res=fact(N)/(fact(N-2)*fact(2));
            System.out.println(res);
        }
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89

3 Answers3

2

5277! is a 17354 digit number.

Rather than calculating fact(N) / (fact(N-2) * fact(2)), you should realize that fact(N) / fact(N-2) is the same as N * (N-1), so if you calculate that instead, your calculation won't overflow.

Alternatively, change fact() to calculate using BigInteger, but you're really wasting time by multiplying 5277 numbers, then multiplying 5275 numbers, and dividing them, just to get a result that can be calculated by multiplying 2 numbers.

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

The maximum number an int can hold is up to:

2 ^ 31 - 1 = 2,147,483,647

However:

12! = 479,001,600
13! = 6,227,020,800

Then, this means that after 12! you cannot hold the value in an int.

While error given by the compiler is not really explicit, it's an overflow

You could use long but that's still:

2 ^ 63 - 1 = 9.223372036854776e18 ~ 9,223,372,036,854,776,000
21! = 5.109094217170944e19 ~ 51,090,942,171,709,440,000

As you can see it still overflows...

So, a better advice would be to use BigInteger class

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • And can u plzz tell me what changes I have to make in my code for it,bcz i really don't know the implementation – Aashish Kalia Aug 17 '17 at 16:49
  • 2
    Read about `BigInteger` class and look for examples first, and try them yourself, then come back if you don't fully understand it (asking an specific question) – Frakcool Aug 17 '17 at 16:50
0

Your calculations are massively overflowing the integer range (that's what the other answers already said). The overflow in itself happens silently, just giving wrong results (clipping all binary digits in front of the trailing 32 bits).

What leads to the java.lang.ArithmeticException: / by zero is that the binary representation of your (fact(N-2)*fact(2)) with N=5277 has more than 32 trailing zeros (in fact, it must be around 4000 trailing zeroes). And clipped to the trailing 32 bits, that's zero. That's where the division by zero happens.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
  • `5277!` has 17354 decimal digits, with 1317 trailing zeroes. It has 57648 binary digits (bits), with 5270 trailing zeroes. – Andreas Aug 17 '17 at 18:41