Advertisement
Guest User

Calculate Factorial using Array

a guest
Apr 3rd, 2015
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.  
  8.         int[] numbers = new int[] {100, 171, 250};
  9.  
  10.         foreach (int n in numbers)
  11.         {
  12.             Console.WriteLine("The factorial of {0} is:", n);
  13.             ArrayFactorial(n);
  14.             Console.WriteLine("\n");
  15.         }
  16.     }
  17.  
  18.     private static void ArrayFactorial(int n)
  19.     {
  20.         int[] a = new int[1000]; //array will have the capacity to store 200 digits.
  21.         int i, j, temp, m, x;
  22.  
  23.         a[0] = 1;  //initializes array with only 1 digit, the digit 1.
  24.         m = 1;    // initializes digit counter
  25.  
  26.         temp = 0; //Initializes carry variable to 0.
  27.         for (i = 1; i <= n; i++)
  28.         {
  29.             for (j = 0; j < m; j++)
  30.             {
  31.                 x = a[j] * i + temp; //x contains the digit by digit product
  32.                 a[j] = x % 10; //Contains the digit to store in position j
  33.                 temp = x / 10; //Contains the carry value that will be stored on later indexes
  34.             }
  35.             do //while loop that will store the carry value on array.
  36.             {
  37.                 a[m] = temp % 10;
  38.                 temp = temp / 10;
  39.                 m++; // increments digit counter
  40.             } while (temp > 0);
  41.         }
  42.  
  43.         //printing answer
  44.         for (i = m - 1; i >= 0; i--)
  45.         {
  46.             Console.Write(a[i]);
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement