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));
}
}
# 1 楼答案
我们可以在Java 8中进行函数分解:
source
# 2 楼答案
简单的一行程序解决方案,虽然在内部它是在做一个循环,因为没有它是不可能的,但你不需要自己做:
# 3 楼答案
这里还有一个帖子,你可能想看看:
Is there a method that calculates a factorial in Java?
此外,这个链接有很多不同的阶乘函数实现,你可以在这里找到你想要的。至少,你会学到很多关于阶乘的知识
http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
# 4 楼答案
有点不切实际,但任何地方都没有显式循环
# 5 楼答案
对伽马函数http://en.wikipedia.org/wiki/Stirling%27s_approximation使用斯特林近似
但这并不精确
# 6 楼答案
你可以预先计算这些值
更严重的是,这实际上是不可行的,因为如果你可能需要做任意多的计算,递归和循环是不可避免的