Advertisement
Ludmil

C# Loops Sum+ N!/XN

Mar 24th, 2014
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. using System.Numerics;
  2. /*Problem 5.    Calculate 1 + 1!/X + 2!/X2 + … + N!/XN
  3. Write a program that, for a given two integer numbers n and x, calculates the sum
  4.   * S= 1 + 1!/x + 2!/x2 + … + n!/xn. Use only one loop. Print the result with 5 digits
  5.  * after the decimal point*/
  6. class Program
  7. {
  8.     static void Main()
  9.     {
  10.         //string strNum;
  11.         //BigInteger
  12.         double xSumSqr = 1;
  13.        // BigInteger
  14.         double nSumFact = 1;
  15.        // BigInteger
  16.         double Sum = 1;
  17.         int n = 4;
  18.         int x = 3;
  19.         int j = 1;
  20.         //Console.WriteLine("Calculate 1 + 1!/X + 2!/X2 + … + N!/XN");
  21.         //do
  22.         //{
  23.         //    Console.Write("Please, enter an unsigned integer number n: ");
  24.         //    Console.Write("Please, enter an integer number x, not equal to 0: ");
  25.         //}
  26.         //while ((!(int.TryParse(strNum = Console.ReadLine(), out x)) || x == 0)
  27.         //    && (!int.TryParse(strNum = Console.ReadLine(), out n)));
  28.         if (n == 0)
  29.         {
  30.             Sum += 1;
  31.         }
  32.         else
  33.         {
  34.             for (int i = 1; i <= n; i++)
  35.             {
  36.                 nSumFact = 1;
  37.                 for ( j = 1; j <= i; j++)
  38.                 {
  39.                     nSumFact *= j;                    
  40.                 }
  41.                 xSumSqr = (int)Math.Pow(x, i);
  42.                 Sum += nSumFact / xSumSqr;
  43.             }
  44.         }
  45.         Console.WriteLine("{0:F10}",Sum);
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement