I am working on a problem from CodeChef where I need to calculate a factorial of n numbers.
The user enters a number that determines how many ints does factorial calculation, and then enters numbers to calculate.
My problem is related to the multiplication itself. For example, if I have int == 5, then the result will be 20 (it will calculate n only by the last factorial, and not by all)
This is where the problem is:
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x _result[x] = _numbersToProcess[x] * y;// Multiply x by y then add to array } }
The outer loop determines how many calculations to perform.
The inner loop calculates factorials by repeating each _numberToProcess index and multiplying it by each number less than the number to be calculated.
The problem is that factorial calculation overwrites itself,
eg:
factorial of 5 result: 20 , but it should be 120 (it is overwritten until it reaches the last factor)
So, I tried the following:
_result[x] = _numbersToProcess[x] *= y;
This obviously matches _numbersToProcess[x] = _numbersToProcess[x] * y;
But this gives a completely different result:
If we enter 5 again, this will exit -1899959296.
I know that I can easily copy and paste from other materials, but I want to know why my method does not lead to the correct conclusion.
Here is the method as a whole:
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate int[] _numbersToProcess = new int[_numbers];// Array of inputs int[] _result = new int[_numbers]; int i = 0; while(i < _numbersToProcess.Length) { _numbersToProcess[i] = int.Parse(Console.ReadLine()); i++; } for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x _result[x] = _numbersToProcess[x] *= y;// Multiply x by y then add to array } } for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x Console.WriteLine(_result[n]);// Write to console } Console.ReadLine();