For loop to calculate factorials

Currently I have this set of code and its meant to calculate factorials.

int numberInt = int.Parse(factorialNumberTextBox.Text);

for (int i = 1; i < numberInt; i++)
{
  numberInt = numberInt * i;
}

factorialAnswerTextBox.Text = numberInt.ToString();

For some reason it doesn’t work and i have no clue why. For example i will input 3 and get the answer as -458131456 which seems really strange.

Any help appreciated. Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

int numberInt = int.Parse(factorialNumberTextBox.Text);
int result = numberInt;

for (int i = 1; i < numberInt; i++)
{
    result = result * i;
}

factorialAnswerTextBox.Text = result.ToString();

on a side note: this would normally NOT be the correct way to calculate factorials.
You’ll need a check on the input before you can begin calculation, in case your starting value is 1 or below, in that case you need to manually return 1.

On another side note: this is also a perfect example of where recursive methods can be useful.

int Factorial(int i)
{
    if (i <= 1)
        return 1;
    return i * Factorial(i - 1);
}

Method 2

A little late to the party:

Func<int, int> factorial = n => n == 0 ? 1 : 
    Enumerable.Range(1, n).Aggregate((acc, x) => acc * x);

Method 3

You can use this (rather elegant) solution:

    Func<int, int> factorial = null; 
    factorial = x => x <= 1 ? 1 : x * factorial(x-1);
    int numberInt = int.Parse(factorialNumberTextBox.Text);
    factorialAnswerTextBox.Text = factorial(numberInt).ToString();

Method 4

public static int Factorial(int facno)
{
    int temno = 1;

    for (int i = 1; i <= facno; i++)
    {
        temno = temno * i;
    }

    return temno;
}

Method 5

i am late to the party but here it is

    public ulong Factorial(uint numb)
    {
        if (numb <= 1) return 1;
        ulong final = 1;
        for (uint i = 1; i <= numb; i++)
        {
            final *= i;
        }
        return final;
    }

Note:
i used un-signed types for better range
as this calculates up to Factorial(65), while normal signed types will give negative values

Method 6

Trying to make a more bulletproof solution for n factorial. Here is one that guards for overflows, as well as negative and zero values of n. Using a result variable of type long (instead of int) allows for “larger” values to be calculated (for long, you can calculate up to and including n = 20).

This code returns 0 if an overflow occurred, but you can change it to do whatever is more appropriate.

    static long nFactorial(int n)
    {
        if (n <= 1)
        {
            return 1;
        }
        long result = 1;
        try
        {
            for (int i = 1; i <= n; i++)
            {
                result = checked(result * i); 
            }
        }
        catch (OverflowException)
        {
            return 0;
        }
        return result;
    }

Method 7

I had to create a factorial method for calculating combinations and tripped over the fact that factorials get very big very fast with relatively small inputs. Here’s my solution without using recursion to avoid stack overflow and implemented using System.Numerics.BigInteger.

static BigInteger factorial(int num) {
    BigInteger result = 1;
    while (num > 1) {
        result *= num--;
    }
    return result;
}

Obviously, you could also using BigInteger for input but my use case was that I was processing int values.

Method 8

use factorial function:

static long Factorial(long number)
    {
    if( number <= 1 )
        return 1;
    else
        return number * Factorial(number - 1);
    }

and then call the function:

long result = Factorial(int.Parse(factorialNumberTextBox.Text));
factorialAnswerTextBox.Text = result.ToString();

Method 9

 int numberInt=1 ;

            for (int i = 1; i <= int.Parse(factorialNumberTextBox.Text); i++)
            {

                numberInt = numberInt * i;
            }

            factorialNumberTextBox.Text = numberInt.ToString();

Method 10

Try this,

int numberInt = int.Parse(textBox1.Text);
        int answer = 1;
        for (int i = 1; i <= numberInt; i++)
        {
            answer = answer * i;
        }

        textBox1.Text = answer.ToString();

Method 11

Two methods are implemented: Recursive and Basic factorial calculation.

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

namespace ConsoleApplication50
{
    class Program
    {
        static void Main(string[] args)
        {

        NumberManipulator manipulator = new NumberManipulator();
        Console.WriteLine("Please Enter Factorial Number:");
        int a= Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("---Basic Calling--");
        Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));

        Console.WriteLine("--Recursively Calling--");
        Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));

        Console.ReadLine();
    }
}

class NumberManipulator
{
    public int factorial(int num)
    {
        int result=1;
        int b = 1;
        do
        {
            result = result * b;
            Console.WriteLine(result);
            b++;
        } while (num >= b);
        return result;
    }

    public int recursively(int num)
    {
        if (num <= 1)
        {
            return 1;
        }
        else
        {
            return recursively(num - 1) * num;
        }
    }
  }
}

Method 12

static void Main()
{
    int numberFactorial = int.Parse(Console.ReadLine());
    int result = numberFactorial;

    for (int i = 1; i < numberFactorial; i++)
    {
        result = result * i;
        Console.WriteLine("{0}*{1}",numberFactorial,i);
    }
    Console.WriteLine(result);
}

Method 13

A nice factorial solution for your nice evening.

int num = Convert.ToInt32(Console.ReadLine());
int fact = 1;
for (int i = num; i > 0; --i)
    fact *= i;
Console.WriteLine(fact);

Method 14

    public static void Main(string[] args)
    {

      string result =   Convert.ToString(GetFactorial(5));
        Console.WriteLine(result);
    }

    internal static int GetFactorial(int factNumber)
    {
        int factorial =1;
        int i = factNumber;            
        while(factNumber>=1)
        {
          factorial = factNumber * factorial;
            factNumber--;
        }
       return  factorial;

    }

Method 15

How about this?

public int FactorialFunction(int Factorial){
        int Product = Factorial -1;
        for(int Number = Factorial - 1; Number < Factorial; Number++ ) {
            Factorial = Product * Factorial;
            Product--;
        }
        return Factorial;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x