Advertisement
Hristo_B

Methods.Factoriel

Jul 5th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Numerics;
  4.  
  5. class CalculatingFactoriel
  6. {
  7.     //Write a program to calculate n! for each n in the range [1..100].
  8.     //Hint: Implement first a method that multiplies a number represented as array of digits by given integer number.
  9.  
  10.     static int[] NumberToArray(string number)
  11.     {
  12.         string digit = "";
  13.         int[] arr = new int[number.Length];
  14.         for (int i = arr.Length - 1, counter = 0; i >= 0; i--, counter++)
  15.         {
  16.             digit += number[i];
  17.             arr[counter] = Convert.ToInt32(digit) % 10;
  18.             digit = "";
  19.  
  20.  
  21.         }
  22.         return arr;
  23.     }
  24.     static int[] Factoriel(int[] numberArr, int[] anotherArr)
  25.     {
  26.         BigInteger productInt = 0;
  27.         for (int i = 0; i < numberArr.Length; i++)
  28.         {
  29.             BigInteger numberpowered = (int)Math.Pow(10, i);
  30.             for (int k = 0; k < anotherArr.Length; k++)
  31.             {
  32.                 BigInteger anotherpowered = (int)Math.Pow(10, k);
  33.                 productInt += anotherArr[k] * anotherpowered * numberArr[i] * numberpowered;
  34.             }
  35.         }
  36.         string productString = productInt.ToString();
  37.         return NumberToArray(productString);
  38.     }
  39.  
  40.     static void Main()
  41.     {
  42.         Console.Write("N = ");
  43.         string n = Console.ReadLine();
  44.        
  45.         int nToNumber = int.Parse(n);
  46.         int[] nFactoriel = Factoriel(NumberToArray("1"), NumberToArray("2"));
  47.         for (int i = 3; i <= nToNumber; i++)
  48.         {
  49.             nFactoriel = Factoriel(nFactoriel, NumberToArray(i.ToString()));
  50.         }
  51.         Console.Write("N! = ");
  52.         for (int i = nFactoriel.Length - 1; i >= 0; i--)
  53.         {
  54.             Console.Write(nFactoriel[i]);
  55.         }
  56.         Console.WriteLine();
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement