简体   繁体   中英

Java: How to solve a large factorial using arrays?

All the solutions online I can find use BigInteger but I have to solve this using arrays.

I'm only a beginner and I even took this to my Computer Science club and even couldn't figure it out.

Every time I enter a number greater than 31 , the output is always zero.

Also, when I enter a number greater than 12 , the output is always incorrect.

Eg fact(13) returns 1932053504 when it should return 6227020800

Here's what I have so far:

import java.util.Scanner;

class Fact
{
    public static void main(String[] args)
    {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter the number you wish to factorial");
        int x = kb.nextInt();
        System.out.println(fact(x));
    }

    public static int fact(int x)
    {
        int[] a = new int[x];

        int product = 1;

        for(int i = 0; i < a.length; i++)
        {
            a[i] = x;
            x--;
        }

        for(int i = 0; i < a.length; i++)
        {
            product = product * a[i];
        }

        return product;
    }
}

Maximum Values Make Large Numbers Terrible

Sadly, because of the maximum values of integers and longs , you are unable to go any larger than

For Longs:

2^63 - 1

9223372036854775807

9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807

and For Ints:

2^31 - 1

2147483647

2 billion 147 million 483 thousand 647

(I put the written names in to show the size)

At any point in time during the calculation you go over these, "maximum values," you will overflow the variable causing it to behave differently than you would expect, sometimes causing weird zeros to form.

Even BigInteger s have problems with this although it can go up to numbers way higher than just longs and ints which is why they is used with methods that generate massive numbers like factorials.

You seem to want to avoid using BigInteger and only use primatives so long will be the largest data type that you can use.

Even if you convert everything over to long (except the array iterators of course), you will only be able to calculate the factorial up to 20 accurately. Anything over that would overflow the variable. This is because 21! goes over the "maximum value" for longs.

In short, you would need to either use BigInteger or create your own class to calculate the factorials for numbers greater than 20.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM