Home > other >  Method works but throws errors for particular numbers
Method works but throws errors for particular numbers

Time:12-14

I wrote a method that calculates the combination of 2 numbers and it works for smaller numbers where n = 10 and r = 3, but when input n as 100 and r as 3 it throws an arithmetic exception " / by zero"

import java.util.Scanner;

public class Combination {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = scan.nextInt();
        System.out.print("\nEnter r: ");
        int r  = scan.nextInt();
        scan.close();
        int ans = factorial(n) / (factorial((n-r)) * factorial(r));
        System.out.print("\nThe combination is: " ans);
    }
    static int factorial(int num) {
        for(int i = num; i>1; --i) {
            num *= (i - 1);
        }
        return num;
    }
}

but i don't know what the problem is. it works for smaller numbers of n.

CodePudding user response:

You're multiplying values which result in a number too big to fit inside an integer.

If you print out the num inside your for loop, you'll notice it eventually either goes negative or to zero. This is due to overflow.

For your example of n=100 and r=3 not even long will do. You'll need to use something like BigInteger.

Keep in mind that using BigInteger will drastically slow down your program when compared to using primitives.

If you're not interested in having such large numbers and were just curious why it wasn't working, you can also use Math.multiplyExact(int x, int y) or Math.multiplyExact(long x, long y) if you're using Java 8 or above.

By using these methods, you'll avoid having to deal with the side-effects of overflow since they will throw an ArithmeticException if the result overflows.

CodePudding user response:

Change the data type of num from int to double

  • Related