2

I'm working on a separate program which has a bunch of gui, so I made a simpler program in an attempt to ask for help.

I don't really know permutations and combinations that well.

Anyway, I have a piece of code here which solves this function:

F (n,r) = n!/(r!(n-r)!)

You can change the n and r in the code and it'll give you the answer for those two inputs.

public class peanuts
{

static int n,r;


public static void main (String[] args)
{

   n= 8;
    r=3;

  int m=1;

    if(n>>1 < r)
        r = n - r;
    for(int o=n+1-r;o<n+1;o++)
        m *= o;
    for(int o=r;o>0;o--)
        m /= o;
    Math.round(m);

      System.out.println ("C("+n+","+r+ ") is "+ m );
}}

I want to modify it slightly so it solves this permutation function:

F (n,r) = n!/(n-r)!)
Sitansu
  • 3,225
  • 8
  • 34
  • 61
munchschair
  • 1,593
  • 3
  • 19
  • 43

2 Answers2

2

Remove the second for loop that divides by r!.

for(int o=r;o>0;o--)
  m /= o;

This divides m by r!. Remove this loop.

Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
2

Formula for calculating the permutation is:

F (n,r) = n!/(n-r)!

Formula for calculating the combination is:

F (n,r) = n!/(r!(n-r)!)

So you just need to remove the second for loop in which you are dividing by factorial r ie, remove this:

for(int o=r;o>0;o--)
  m /= o;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331