+ 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.

10th Jul 2016, 9:35 AM
Aastha Aneja
Aastha Aneja - avatar
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 👆😂
10th Jul 2016, 4:22 PM
Erwin Mesias
Erwin Mesias - avatar
+ 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; }
10th Jul 2016, 5:13 PM
Aastha Aneja
Aastha Aneja - avatar
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?
10th Jul 2016, 1:00 PM
Aastha Aneja
Aastha Aneja - avatar
0
sure😂😂
10th Jul 2016, 1:10 PM
Aastha Aneja
Aastha Aneja - avatar
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😅
10th Jul 2016, 1:45 PM
Aastha Aneja
Aastha Aneja - avatar
10th Jul 2016, 1:50 PM
Aastha Aneja
Aastha Aneja - avatar
0
@Erwin send me the code to anejaaastha@gmail.com when u r done😊
10th Jul 2016, 2:51 PM
Aastha Aneja
Aastha Aneja - avatar
0
@Aastha, with your correction, you removed the limit variable declaration. It will now give you errors 😂
10th Jul 2016, 5:26 PM
Erwin Mesias
Erwin Mesias - avatar
0
oh yeah😂😂😂😂
10th Jul 2016, 5:31 PM
Aastha Aneja
Aastha Aneja - avatar