Friday 20 April 2012

Balls and the ways..

N balls are present in a basket. In one iteration either one ball or two balls can be withdrawn from the basket. Iterations are performed until basket gets empty. Find number of possible ways (write code).

#include "iostream"
using namespace std;
// Is this the Best way to find a factorial
int factorial(int n)
{
 if(n==0 || n==1)
  return 1;


int i = n-1;
while(i>1)
{
  n = n*i;
  i--;
}


 return n*factorial(n-1);
}
int main()
{
 int noOfBalls;
 cin>>noOfBalls;
 // Initalization.
 int num1,num2;
 int totalways;
 if(noOfballs <= 0)
 {
  cout<<"0";
  return;
 }
 // Initialization. We dont calculate one obvious way of using all 1s
 num1 = noOfBalls-2;
 num2=1;
 totalways = 1;


 while(num1 >= 0)
 {
  if(num1==0) { totalways++; break; }
  totalways += (factorial(num1+num2) / (factorial(num1) * factorial(num2)));
  num2++;
  num1 = num1-2;
 }
 cout<<totalways;
 return 0;

1 comment:

Andy said...

You got a fundamental problem here.