user2344868
user2344868

Reputation: 39

Recursion issue?

So this is my first recursion function (I hope!) and I'm unsure why it isn't working, (aka red lines) any ideas?

int myFactorial(int C) { //underlined, expects ";"

    int n = Integer.parseInt(objectsChooseField.getText());
    int r = Integer.parseInt(chooseFromField.getText());

    if (C == 1){
        return 1; //underlined, cannot return value from method whose result type is void
    }
    return (C*(myFactorial(n/(r(n-r))))); //underlined
}

Upvotes: 1

Views: 243

Answers (4)

Jemolah
Jemolah

Reputation: 2192

OK. So you have the ActionPerformed method. Put in the code like:

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    int n = Integer.parseInt(objectsChooseField.getText());
    int r = Integer.parseInt(chooseFromField.getText());
    int result = faculty( n ) / ( faculty( r ) * ( n - r ));
    //--- Output result to somewhere
}

And the faculty computation method itself:

/** Computes the faculty of n */
public int faculty( n ) {
  if ( n > 1 )
    return n * faculty( n - 1 );
  return 1;
}

Upvotes: 0

Jemolah
Jemolah

Reputation: 2192

Your equation does not state any recursion. The faculty could by computed with recursion.

public int MyMethod() {
int n = Integer.parseInt(objectsChooseField.getText());
int r = Integer.parseInt(chooseFromField.getText());
int result = C( n, r );
}

public int C( int n, int r ) {
  int res = faculty( n ) / ( faculty( r ) * ( n - r ));
  return res;
}

//--- Computing the faculty itself could be done by recursion :-)
public int faculty( n ) {
  if ( n > 1 )
    return n * faculty( n - 1 );
  return 1;
}

Upvotes: 0

unxnut
unxnut

Reputation: 8839

Shouldn't the recusive statement be:

return ( C * myFactorial ( C - 1 ) );

Upvotes: 2

zw324
zw324

Reputation: 27210

Here: r(n-r).

r is not a function, but an local variable int.

Do you mean r * (n - r)?

Upvotes: 10

Related Questions