I was assigned to write a program based off the following code that can display 50 factorial. Since the primitive types cannot fit such a large number, I have been asked to use an integer array and use individual slots for "parts" of the large number. Here is the code I have been given to code around...
class Fifty
{
public static void main(String[] args)
{
System.out.println("0! = " + fact(0));
System.out.println("1! = " + fact(1));
System.out.println("5! = " + fact(5));
System.out.println("50!= " + fact(50));
}
public static int fact(int n)
{
int product = 1;
for (int i = 2; i <= n; i++)
{
product = product * i;
}
return product;
}
}
And here is the instructional note I have been given
Fifty Factorial
use an array as you use a product in your program.
Int type cannot fit the value of 50!, so we use an array for every individual digit in its value.
if a slot is greater than 9...
0 6 12 0
0 7 2 0 Carry the one over, keep the two set where it is.
product[i] / 10 will give you what to carry product[i] % 10 will give you what to keep Multiply this by the next factorial value and repeat until finished and you have a definite answer to display
Now, I know how to use this method, what I don't know is how to actually create the array with the values I need. How do I get the answer to 50! "broken up" into the pieces of the array?
You can make this more achievable by breaking it down into some component parts.
You will need a method to convert integers into their array of digits representations, so implement, with unit tests, the method:
public static int[] intToDigitArray(int input) {
//e.g. 50 becomes [5,0] (or [0,5] if you prefer)
}
You will need a method which can multiply two array of digit representations:
public static int[] multiply(int[] a, int[] b) {
//e.g. multiply([1,2] , [1,1]) becomes [1,3,2]
}
If you have to use proper arrays rather than for example array lists, you also need to worry about the size of the resulting array to allocate within multiply. So you need a method such as:
public static int[] allocateArray(int[] a, int[] b) {
//If I have two arrays of size x and y, whats the max size I need for the output array?
//initialise with zeros?
}
If you start implementing these functions, testing as you go, and come back with specific questions when you get stuck, you'll probably get more useful answers. I haven't given any implementations above, since it is a homework question and I assume you're not looking to be given a complete solution.