0
About The Combination Formula[SOLVED]
The combination formula is as follows: n! --------------- r! * (n - r)! Basically, it's supposed to be used to find the total possible outcomes for a situation where order doesn't matter. A more code-like version would look like: factorial(n) / (factorial(r) * factorial(n - r)) This means that if n was equal to 14, and r was equal to 2, the result would be 91. But currently, my program returns 1. How can I fix this? https://code.sololearn.com/cjwIZa7kdGxu/?ref=app
9 Answers
+ 1
If you want to use really big numbers you can use BigInteger
+ 7
public class Program
{
public static long factorial(int num) //just a recursive factorial function
{
if (num<= 1)
{
return 1;
}
else
{
return num * factorial(num - 1);
}
}
public static long combination(int n, int r) //combination formula is as follows: n! / (r! * (n - r)!); this is the equation that I followed, but when trying out the arguments 14 and 2, 1 was returned instead of 91, which is the correct answer
{
return factorial(n) / (factorial(r) * factorial(n - r));
}
public static void main(String[] args) {
System.out.println(combination(12, 2));
}
}
+ 5
Edit the code recently and it should work, it gives me 91. Copy the code of top y check
+ 2
You need to use long instead of int cause int has 32 bit and 12! *14! is bigger than 2^32 so there is an overflow
+ 1
Jesus Eduardo Canul Koyoc double is for double precision of floating point numbers but the combinational formula is not a floating number so long would be better
+ 1
Jianmin Chen BigInteger is not a type its a class and if you want to create an instance of this "type" you need to create an object of BigInteger. So you cant multiply with * you need to call a function.
If you use it i would recommend reading the documentation.
0
Jnn, thanks for catching the error! Coming from a programming language like Python, I'm not prepared to deal with statically-typed ones where there are specific types.đ
I'll try BigInteger when I have the time.
Thanks for helping too, Jesus Eduardo Canul Koyoc. Unfortunately, I tried 14 and 2, and it still returns 1.
0
Sorry, Jesus Eduardo Canul Koyoc, my mistake. You're right, it does output 91; I must have given the wrong input. Jnn, I was talking about the different data types in Java, E.G. int, char; are they considered data types in Java? I know strings and integers, along with others like lists, would all be considered objects in Python, but I'm not so sure about Java, since I'm a beginner.
0
Thanks so much, Jesus Eduardo Canul Koyoc and Jnn! I've changed the use of integers to the BigInteger class.