Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# to calculate factorial

Tags:

c#

factorial

I have this code that gets an input from the user and calculate its factorial and the factorial for less than the input number, but I keep getting the factorial for the first number only and the rest is 0. It should be like this: For example, if the input is 5:

5! = 120

4! = 24

3! = 6

2! = 4

1! = 1

How do I make the loop go throw all the numbers below the input number?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace multiple_factorials
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, n;

            Console.WriteLine(".....................[Application 1].....................\n\n");
            Console.WriteLine("Please enter a number to get its factorial: ");
            num = Convert.ToInt32(Console.ReadLine());

            n = num; // Assign n to num

            while (num > 0)
            {
                for (int i = n - 1; i > 0; i--)
                {
                   n *= i;
                }
                Console.WriteLine("Factorial of {0}! = {1}\n", num, n);
                num--;
            }
        }
    }
}
like image 731
Ahmad Khalil Avatar asked Sep 06 '25 03:09

Ahmad Khalil


2 Answers

You've included System.Linq so I've put LINQ solution:

 int n = 5;

 // result == 120
 int result = Enumerable.Range(1, n).Aggregate(1, (p, item) => p * item);

However, LINQ is overkill here, and the for loop is more readable. To print out all the lines:

int num = 5;

String result = String.Join(Environment.NewLine,
  Enumerable.Range(1, num)
    .Reverse()
    .Select((index) =>
      String.Format("Factorial of {0}! = {1}\n",
                    index,
                    Enumerable.Range(1, index).Aggregate(1, (p, item) => p * item))));

Console.Write(result);
like image 65
Dmitry Bychenko Avatar answered Sep 07 '25 21:09

Dmitry Bychenko


To answer you question now you have acctually posted it:

My question is How to make the loop go throw all the numbers below the input number?

With a loop

for(int i = input; i > 0; i--)

Will count down from input (lets say 5) to 1 {5, 4, 3, 2, 1}

then you simply multiply together

int result = 1;
for(int i = input; i > 0; i--) 
    result *= i; 

Proof: int input = 4; int result = 1; for(int i = input; i > 0; i--) result *= i;

Console.WriteLine("Result=" + result);

Output: 24

A better way Using Recusion

public int Factorial(int f)
{
    if(f == 0)
        return 1;
    else
        return f * Factorial(f-1); 
}

so calling Factorial(5) gives a result of 120 etc.

like image 40
Alex Anderson Avatar answered Sep 07 '25 23:09

Alex Anderson