2

我需要在不使用循环或递归的情况下在 java 中找到阶乘?因此,如果有任何方法,请提供帮助。谢谢

4

6 回答 6

7

对 Gamma 函数使用斯特林近似http://en.wikipedia.org/wiki/Stirling%27s_approximation

在此处输入图像描述

但这并不精确。

于 2012-11-17T19:02:55.440 回答
2

这里有另一个帖子,您可能想看看:

有没有一种方法可以在 Java 中计算阶乘?

另外——这个链接有很多不同的阶乘函数实现——你可能会在这里找到你要找的东西。至少,你会学到很多关于阶乘的知识。

http://www.luschny.de/math/factorial/FastFactorialFunctions.htm

于 2012-11-17T19:06:28.070 回答
1

有点不切实际,但在任何地方都没有明确的循环。

import javax.swing.Timer;
import java.awt.event.*;
import java.util.concurrent.ArrayBlockingQueue;

public class Fac {
    public static int fac(final int _n) {
        final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
        final Timer timer = new Timer(0, null);
        timer.addActionListener(new ActionListener() {
            int result = 1;
            int n = _n;
            public void actionPerformed(ActionEvent e) {
                result *= n;
                n--;
                if(n == 0) {
                    try {
                        queue.put(result);
                    } catch(Exception ex) {
                    }
                    timer.stop();
                }
            }
        });
        timer.start();
        int result = 0;
        try {
            result = queue.take();
        } catch(Exception ex) {
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(fac(10));
    }
}
于 2012-11-17T19:54:41.400 回答
1

简单的一个班轮解决方案,虽然在内部它正在做一个循环,因为没有它就不可能,但你不需要自己做:

Long factorialNumber = LongStream.rangeClosed(2, N).reduce(1, Math::multiplyExact);
于 2016-01-28T21:51:08.390 回答
0

您预先计算值。

更严重的是,这并不是真正可行的,因为如果您可能需要进行任意多的计算,递归和循环是不可避免的。

于 2012-11-17T18:56:03.420 回答
-1

我们可以在 Java 8 中做一个函数阶乘:

package com.promindis.jdk8;

import java.math.BigInteger;
import static java.math.BigInteger.*;

public class Factorial implements TCO {

  private TailCall<BigInteger> factorialTCO(
    final BigInteger fact, final BigInteger remaining) {
    if (remaining.equals(ONE))
      return done(fact);
    else
      return call(() ->
        factorialTCO(fact.multiply(remaining), dec(remaining)));
  }

  private BigInteger dec(final BigInteger remaining) {
    return remaining.subtract(ONE);
  }

  private BigInteger apply(final String from) {
    return factorialTCO(ONE, new BigInteger(from)).invoke();
  }

  public static void main(final String[] args) {
    System.out.println(new Factorial().apply("5"));
    System.out.println(new Factorial().apply("100"));

  }
}

来源

于 2013-08-23T15:43:59.053 回答