Basically what i am saying for the factorial is since you can't fit 100! in any numerical data type, store the value in a string. For example, you couldn't store a value like 999999999999999999999999999999999 as a double because it's far too large, but you could put that in a string. But then, it wouldn't be a numerical data type, so you couldn't multiply it by by a numerical value using the * operator. That means you would have to write a method to multiply a numerical integer by a string that represents a number. To do that, think back to elementary school math when you first learned to multiply. You start at the left of the big number, and multiply each digit by the small number. Then carry, and you know the rest. Now, all you have to do is implement that in code.
Here is a method i just wrote that should do that
csharp
/// <summary>
/// Multiplies a string representing a number by a numerical int.
/// </summary>
public static string MultiplyString(int NumericValue, string StringValue)
{
string Product = StringValue;
int Carry = 0; //This will hold the carry
int Position;
//Illiterate through each digit in StringValue
for (Position = StringValue.Length; Position >= 1; Position--)
{
string Digit = Product.Substring(Position - 1, 1); //Get the digit in StringValue at the current index
int DigitInt = int.Parse(Digit); //Parse that digit to an int
int CurrentProduct = DigitInt * NumericValue; //Multiply it by NumericValue
if (Carry != 0)
{
CurrentProduct += Carry % 10; // add the last digit in carry onto CurrentProduct
Carry /= 10; //Take the digit we just added onto CurrentProduct off Carry
}
int CurrentCarry = CurrentProduct / 10; //Take all but the last digit off CurrentProduct and add it to carry.
CurrentProduct %= 10; //Make CurrentProduct so it only holds the last digit
Carry += CurrentCarry; //Add CurrentCarry onto Carry
//Lastly, replace the current digit in Product with CurrentProduct
Product = Product.Remove(Position - 1, 1);
Product = Product.Insert(Position - 1, CurrentProduct.ToString());
}
//Add the remaining carry onto the front of Product
if (Carry != 0)
{
Product = Carry.ToString() + Product;
}
return Product;
}
Works like a charm. Pass that a string number as big as your heart desires.
Now then, to make that do a factorial, try this
csharp
string b;
while (a <= 100)
{
b = MultiplyString( a, b );
a++;
}
This post has been edited by jacobjordan: 30 Jun, 2009 - 01:54 PM