用Java解决ln(N!)的算法

时间:2015-03-08 11:25:49

标签: java algorithm data-structures

我需要计算ln(n!)

import java.util.Scanner;

public class App {
    public void fact() {
        System.out.println("Enter The integer");
        Scanner ns = new Scanner(System.in);

        int n = ns.nextInt();
if (n == 0) {
            System.out.println("Factorial is " + 1);
System.out.println("Log OF 0 is Undefined!! ");
}
if(n!=0) {
        double a=1;
        for(     int z=1; z<=n;z++) {
            a*=z;

        }
        System.out.println("Fact is"+a);



System.out.println("Log of ln(N!) is "+ Math.log(a));
}
    }


    public static void main(String[] args) {
        App ap = new App();
        ap.fact();

    }
}

我不知道Maths.log函数究竟出了什么问题。我做对了吗?它没有给我一个合适的答案。

2 个答案:

答案 0 :(得分:3)

我怀疑你在这里遇到integer overflow

注意n!增长非常快,对于任何n> 12,你会得到一个不能整数的数字,你应该想到一个聪明的方法来不完全计算n!并且仍然得到正确的结果。

以下提示:

log(a * b)= log(a)+ log(b)

答案 1 :(得分:1)

您的任务是斯特林近似的主题:http://en.wikipedia.org/wiki/Stirling%27s_approximation

相关问题