Skip to content

Calculate factorial of 50 using array only in java

I’m a total beginner of java. I have a homework to write a complete program that calculates the factorial of 50 using array. I can’t use any method like biginteger. I can only use array because my professor wants us to understand the logic behind, I guess… However, he didn’t really teach us the detail of array, so I’m really confused here.

Basically, I’m trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it’s a huge number..)

I tried to understand what’s the logic behind, but I really can’t figure it out.. So far I have this on my mind.

import java.util.Scanner;
class Factorial
    public static void main(String[] args)
        int n;
        Scanner kb = new Scanner(;
        System.out.println("Enter n");
        n = kb.nextInt();
        System.out.println(n +"! = " + fact(n));

    public static int fact(int n)
        int product = 1;
        int[] a = new int[100];
        a[0] = 1;

        for (int j = 2; j < a.length; j++)
            for(; n >= 1; n--)
                product = product * n;

                a[j-1] = n;
                a[j] = a[j]/10;
                a[j+1] = a[j]%10;


        return product;

But it doesn’t show me the factorial of 50. it shows me 0 as the result, so apparently, it’s not working.

I’m trying to use one method (fact()), but I’m not sure that’s the right way to do. My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly. So I’m trying to use that for this homework.

Does anyone have an idea for this homework? Please help me!

And sorry for the confusing instruction… I’m confused also, so please forgive me.

FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000



Try this.

static int[] fact(int n) {
    int[] r = new int[100];
    r[0] = 1;
    for (int i = 1; i <= n; ++i) {
        int carry = 0;
        for (int j = 0; j < r.length; ++j) {
            int x = r[j] * i + carry;
            r[j] = x % 10;
            carry = x / 10;
    return r;


int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
while (i >= 0)
// -> 30414093201713378043612608166064768844377641568960512000000000000
1 People found this is helpful