For loop to calculate factorials

孤者浪人 提交于 2019-11-27 01:23:21

问题


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


回答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);
}



回答2:


A little late to the party:

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



回答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();



回答4:


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

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

    return temno;
}



回答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




回答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;
    }



回答7:


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();



回答8:


 int numberInt=1 ;

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

                numberInt = numberInt * i;
            }

            factorialNumberTextBox.Text = numberInt.ToString();



回答9:


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();



回答10:


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;
        }
    }
  }
}



回答11:


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);
}



回答12:


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.




回答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);



回答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;

    }



回答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;
}


来源:https://stackoverflow.com/questions/16583665/for-loop-to-calculate-factorials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!