Write a method called factorial that takes an integer parameter n and calculates
ID: 3854865 • Letter: W
Question
Write a method called factorial that takes an integer parameter n and calculates n!, which is the product of the integers 1 through n. You can use either a for loop or try recursion to write this method.
Write another method called choose that takes two integer parameters n and k that calculates and returns the n th row k th term in pascal’s triangle. Calculators typically have this function available on them denoted either as nCk or as n k . It is used in combinatorics to count the number of ways we can choose k objects from a set of n unique objects, so assume 0 k n. The explicit formula makes use of your factorial method:
k!/k!(n-k)!
Explanation / Answer
Hi,
Here is the working code, i have added comments to help you understand.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
System.out.println(factorial(5));
System.out.println(Combination(5,2));
}
static double Combination(int x, int y) {
if (y < 0 || y > x) return 0;
double a = 1.0, b = 1.0;
for (int i = 1; i <= y; i++) {
a = a*i; // denomiator
b =b* (x + 1 - i); //numerator
/* since n!/k!(n-k)! boils down to n*n-1..k times/k! */
}
return b / a;
}
static int factorial(int number)// factorial
{
int fact=1;
for(int i=1;i<=number;i++){
fact=fact*i; //iteratively multiply from 1 to number
}
return fact;
}
}
Thumbs up if this was helpful,otherwise let me know in comments. Good day
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.