在Java中查找大数的阶乘 [英] Find factorial of large numbers in Java

查看:127
本文介绍了在Java中查找大数的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到大量的阶乘,例如8785856以典型的方式使用for-loop和double数据类型。

I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.

但它显示无穷大的结果,可能是因为它超出了它的限制。

But it is displaying infinity as the result, may be because it is exceeding its limit.

所以请指导我找到一个非常大数的阶乘的方法。

So please guide me the way to find the factorial of a very large number.

我的代码:

class abc
{
    public static void main (String[]args)
    {
        double fact=1;
        for(int i=1;i<=8785856;i++)
        {
            fact=fact*i;
        }

        System.out.println(fact);
    }
}

输出: -

Infinity

我是新来的Java,但已经学习了一些IO处理的概念和所有。

I am new to Java but have learned some concepts of IO-handling and all.

推荐答案

public static void main(String[] args) {
    BigInteger fact = BigInteger.valueOf(1);
    for (int i = 1; i <= 8785856; i++)
        fact = fact.multiply(BigInteger.valueOf(i));
    System.out.println(fact);
}

这篇关于在Java中查找大数的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆