views:

212

answers:

5

I am practicing recursion and I can't see why this method does not seem to work. Any ideas?

    public void fact()
    {
        fact(5);
    }

    public int fact(int n)
    {
        if(n == 1){
            return 1;
        }
        return n * (fact(n-1));
    }
}

Thanks

+8  A: 

Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.

Anthony Forloney
+1  A: 

Works fine. You're not assigning it to anything. Here's a test that'll prove it works.

@Test
public void testYourFactorialMethod() {
    assertEquals(120, fact(5));
}
arcticpenguin
Isn't `assertEquals()` a JUnit API method? I'm guessing JUnit's not already enabled here, so you should probably be a little more explicit. If it's actually a regular API method, _mea culpa_.
Lord Torgamus
Yes - it's JUnit - all I'm trying to show is that his method works. If you read my comment, I'm not suggesting he insert my code anywhere.
arcticpenguin
A: 

It is totaly wrong to write Fibonacci with recursive methods!!

It is an old famous example for how a good/bad Algorythm affect any project

if you write Fibonatcci recursive, for calculating 120 you need 36 year toget the result!!!!!!

public static int Fibonacci(int x)
{  // bad fibonacci recursive code
if (x <= 1)
      return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}

in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function

using System; using System.Collections.Generic; using System.Numerics; //needs a ref. to this assembly

namespace Fibonaci
{
 public class CFibonacci
 {
   public static int Fibonacci(int x)
   {
       if (x <= 1)
           return 1;
       return Fibonacci(x - 1) + Fibonacci(x - 2);
   }

   public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
   {
       BigInteger previous = 0;
       BigInteger current = 1;

       for (Int64 y = 1; y <= toNumber; y++)
       {
           var auxiliar = current;
           current += previous;
           previous = auxiliar;
           yield return current;
       }
   }
 }
}

and you can use it like

using System;
using System.Linq;

namespace Fibonaci
{
 class Program
 {
   static void Main()
   {
       foreach (var i in CFibonacci.BigFib(10))
       {
           Console.WriteLine("{0}", i);
       }

       var num = 12000;
       var fib = CFibonacci.BigFib(num).Last();
       Console.WriteLine("fib({0})={1}", num, fib);

       Console.WriteLine("Press a key...");
       Console.ReadKey();
   }
 }
}

and in this case you can calculate 12000 less than a second. so

Using Recursive methos is not always a good idea

Above code imported from Vahid Nasiri blog whiche wrote in Persian

Nasser Hadjloo
whose question are you answering here?
Hendrik
Isn't he doing Factorial, not Fibonacci?
glowcoder
-1: While recursion may not be the optimal way to write a factorial method, it _is_ a simple example for introducing the concept of recursion. Don't make assumptions about why an asker is asking a question. Also, a calculation of 120 comes from fact(5); that certainly does not take 36 years to process.
Lord Torgamus
Your algorithm takes time O(n) to compute `Fibonacci(n)` which is shockingly bad. Your comment demonstrates that neither recursion nor iteration is the issue. The issue is using a good algorithm.
+3  A: 

The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:

public class Factorial {
    public static String fact(int n) {
        if(n == 1){
            return "1";
        }
        return n + " * " + (fact(n-1)); // what happens if you switch the order?
    }
    public static void main(String[] args) {
        System.out.println(fact(5));
        // prints "5 * 4 * 3 * 2 * 1"
    }
}
polygenelubricants
+1 for hot jazz.
Lord Torgamus
A: 

A simplified version of your code:

public int fact(int n)
{
    if(n == 1){
        return 1;
    }
    return n * (fact(n-1));
}

could be just:

public int fact(int n)
{
    return n == 1 ? 1 : n * fact(n - 1);
}

but your code is not wrong, this is just another style (if you are not used to ternary operator keep the way it is). I prefer use the ternary operator in these cases (observe that the code is side effect free).

Jonas Fagundes
There's nothing wrong with the algorithm, as 3 other posters have said 7 hours ago. The OP simply was not doing any program output.
Charlie Salts
But his code style is confusing. Two exit points, an non-explicit else and unnecessary parenthesis. That is my point. The question is more than answered.
Jonas Fagundes
Nothing wrong with the two returns. Besides, a beginner would probably struggle with understanding the use of the conditional operator.
Helper Method