+ 5
what can i do to make this code more efficient?
static int fact(int num) { if(num==0||num==1) return 1; else return num*fact(num-1); } This code doesn't give correct answer if I want to calculate the factorial of numbers from 1-100 like for numbers like factorial of 95 or 100, int can't store such large values.
9 Answers
+ 3
@Aastha,
HERE IT IS.
private static string FactorialOf(string str)
{
int limit = int.Parse(str);
if (limit > 1)
{
for (int j = 1; j < limit; j++)
{
List<int> numArr = new List<int>();
for (int i = str.Length-1; i >= 0 ; i--)
numArr.Add(int.Parse(str[i].ToString()));
List<int> answerArr = new List<int>();
int temp = 0;
for (int i = 0; i < numArr.Count; i++)
{
int x = numArr.ElementAt(i) * j + temp;
answerArr.Add(x % 10);
temp = x / 10;
}
while (temp > 0)
{
answerArr.Add(temp % 10);
temp /= 10;
}
answerArr.Reverse();
str = "";
foreach (int i in answerArr)
str += i;
}
return str;
}
else return "1";
}
Compare its answers with Windows Calculator for you to be sure 😁😁😁
Hope that solves it 😂
Don't forget my upVote 👆😂
+ 1
@Erwin n the crct ulong code will be this-
private static ulong FactorialOf(ulong i)
{
ulong i=1;
if (i > 1)
{
for ( ulong x = 1; x <=limit; x++)
i *= x;
return i;
}
else return 1;
}
0
that was surely helpful @Erwin and also does ulong stand for unsigned long? what if I want my program to calculate the factorial of 100?
0
sure😂😂
0
@Erwin Are u on Codechef? Well, they had a solution for this problem using integer arrays but I couldn't understand much of it😅
0
@Erwin check this out https://www.codechef.com/wiki/tutorial-small-factorials
0
@Erwin send me the code to anejaaastha@gmail.com when u r done😊
0
@Aastha, with your correction, you removed the limit variable declaration. It will now give you errors 😂
0
oh yeah😂😂😂😂