SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:6 | ISBN:9780132830317 | Edition: 5

Question

The formula for computing the number of ways of choosing r different things from a set of n things is the following:

C(n, r)= n!/(r!*(n – r)!)

The factorial method n! is defined by

n!= n*(n – 1)*(n – 2)*...*1

Discover a recursive version of the formula for C(n , r) and write a recursive method that computes the value of the formula. Place the method in a class that has a main that tests the method.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.*;
public class FactorialDemo 
{

	public static void main(String args[])
	{
		int n,r;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter number of elements(n): ");
		n= input.nextInt();
		System.out.print("Enter size(r): ");
		r = input.nextInt();
System.out.println("Total " + 	computeWays(n, r) + " ways to choose " + r + " different objects.");
	}
	public static int factorial(int n) 
	{

		if (n == 1)
			return 1;
		else
			return n * factorial(n - 1);
	}

	public static int computeWays(	int x, int y)
	{

		return (factorial(x)) / (factorial(y) * factorial(x - y));
	}

}

OUTPUT:

Enter number of elements(n): 5
Enter size(r): 4
Total 5 ways to choose 4 different objects.

 

0 0

Discussions

Post the discussion to improve the above solution.