Advertisement
ivandrofly

Factorial C# v2

Jun 3rd, 2014
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Factorial
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             int val;
  10.             while (!int.TryParse(Console.ReadLine(), out val))
  11.             {
  12.                 Console.WriteLine("Enter number: 2-9");
  13.             }
  14.             ShowFactoria(fromNum: val); // this will do what you asked @abdul :)
  15.  
  16.     /*
  17.             int factorial;
  18.             while (!int.TryParse(Console.ReadLine(), out factorial))
  19.             {
  20.                 Console.WriteLine("Invalid number entered, make sure you entered a n: 0-10");
  21.             }
  22.             int result = 0;
  23.             bool hit = true;
  24.             for (int i = factorial - 1; i > 0; i--)
  25.             {
  26.                 if (hit)
  27.                 {
  28.                     result = factorial;
  29.                     hit = false;
  30.                 }
  31.                 result *= i;
  32.             }
  33.             Console.WriteLine(result);
  34.     */
  35.             Console.ReadLine();
  36.         }
  37.         private static void ShowFactoria(int fromNum, int to = 0)
  38.         {
  39.             if (fromNum < to)
  40.             {
  41.                 Console.WriteLine("from can't be less than to!!!");
  42.                 return;
  43.             }
  44.             if (to < -1)
  45.             {
  46.                 Console.WriteLine("to can't be less than 0");
  47.             }
  48.             // You can do some other check here...
  49.  
  50.             long temp = 0;
  51.             bool hit = true;
  52.             long result = 0;
  53.             // 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
  54.             for (int i = fromNum; i > to; i--)
  55.             {
  56.                 if (hit)
  57.                 {
  58.                     temp = i * (i - 1);
  59.                     hit = !hit;
  60.                 }
  61.                 else
  62.                 {
  63.                     temp *= (i - 1);
  64.                 }
  65.                 if (i - 1 > 1)
  66.                 {
  67.                     Console.WriteLine(" + {0}", temp);
  68.                     result += temp;
  69.                 }
  70.                 //Console.WriteLine(string.Format("{0} * "))
  71.             }
  72.             Console.WriteLine("The addition of the !{0} shriek is: {1}", fromNum, result);
  73.             Console.ReadLine();
  74.         }
  75.     }
  76. }
  77. By: @ivandrofly
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement