Java 基本递归方法 - 阶乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2802775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:00:27  来源:igfitidea点击:

Basic recursive method - factorial

javarecursionfactorial

提问by bob

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

谢谢

采纳答案by Anthony Forloney

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

您的代码似乎可以工作,但您没有对返回的值、put 方法调用fact或 afact(5)内部进行任何操作,System.out.println然后看看您得到了什么。

回答by andyczerwonka

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));
}

回答by Nasser Hadjloo

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 120you need 36 year toget the result!!!!!!

如果你写斐波那契递归,计算120你需要36年才能得到结果!!!!!!

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

在 dot net 4.0 中有一个新的类型名称 BigInteger,您可以使用它来制作更好的功能

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

使用系统;使用 System.Collections.Generic; 使用 System.Numerics;//需要一个参考。到这个大会

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 12000less than a second. so

在这种情况下,您可以计算12000不到一秒钟。所以

Using Recursive methos is not always a good idea

使用递归方法并不总是一个好主意

Above code imported from Vahid Nasiri blog whiche wrote in Persian

以上代码从Vahid Nasiri 博客导入,该博客用波斯语编写

回答by polygenelubricants

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

递归部分很好;你只是没有使用它的return价值,它被丢弃了。这是您的阶乘代码的完整 Java 应用程序,出于教育目的而略加修饰:

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"
    }
}

回答by Jonas Fagundes

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).

但是你的代码没有错,这只是另一种风格(如果你不习惯三元运算符保持原样)。在这些情况下,我更喜欢使用三元运算符(注意代码没有副作用)。

回答by user1730535

public class Recursive {

    public static void main(String[] argss) {
        System.out.print(fac(3));
    }
    public static int fac(int n) {
        int value = 0;
        if (n == 0) {
            value = 1;
        } else {
            value = n * fac(n - 1);
        }
        return value;
    }
}
// out put 6

回答by Amruth M Raj

static int factorial(int x) {    
    int result;    
    if (x == 1) {    
        return 1;    
    }    
    // Call the same method with argument x-1    
    result = factorial(x – 1) * x;    
    return result;    
}

For complete example check this

对于完整的例子,检查这个

http://answersz.com/factorial-program-in-java-using-recursion/

http://answersz.com/factorial-program-in-java-using-recursion/

回答by Alex Mapley

Try something like this: (Or maybe try this directly)

尝试这样的事情:(或者直接尝试)

public class factorial {

    private static int factorial( int n ){
        if (n > 1)  {
            return n * (factorial(n-1));
        } else {
            return 1;
        }
    }

    public static void main(String[] args) {
        System.out.println(factorial(100));
    }
}