Advertisement
ntodorova

06_CalculateSum

Nov 14th, 2012
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.82 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 6. Write a program that, for a given two integer numbers N and X,
  5.  * calculates the sum S = 1 + 1!/X + 2!/X2 + … + N!/XN
  6.  */
  7. class CalculateSum
  8. {
  9.     static void Main()
  10.     {
  11.         decimal n;
  12.         decimal x;
  13.         decimal sum = 0.00m;
  14.         decimal factoriel = 1.00m;
  15.         decimal power = 1.00m;
  16.  
  17.         Console.Write("N = ");
  18.         string strN = Console.ReadLine();
  19.  
  20.         Console.Write("X = ");
  21.         string strX = Console.ReadLine();
  22.  
  23.         if (!decimal.TryParse(strN, out n))
  24.         {
  25.             Console.WriteLine("Invalid number: {0}", strN);
  26.         }
  27.         else if (!decimal.TryParse(strX, out x))
  28.         {
  29.             Console.WriteLine("Invalid number: {0}", strX);
  30.         }
  31.         else
  32.         {
  33.             for (int i = 1; i <= n; i++)
  34.             {
  35.                 factoriel *= i;
  36.                 power *= x;
  37.  
  38.                 sum += factoriel / power;
  39.             }
  40.  
  41.             Console.WriteLine("The sum is: {0}", 1 + sum);
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement