Click here to Skip to main content
15,069,020 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi Team

I need some help as to write factorial recursion in c#, below is my thought around writing this in c# the algorithm.

What I have tried:

C#
// C# program to find factorial 
// of given number 
using System; 

class Test { 
	// method to find factorial 
	// of given number 
	static int factorial(int n) 
	{ 
		if (n == 0) 
			return 1; 

		return n * factorial(n - 1); 
	} 

	// Driver method 
	public static void Main() 
	{ 
		int num = 5; 
		Console.WriteLine("Factorial of "
						+ num + " is " + factorial(5)); 
	} 
} 
Posted
Updated 11-Nov-20 10:46am
v2
Comments
Richard MacCutchan 11-Nov-20 15:57pm
   
What is wrong with that?
CPallini 11-Nov-20 16:01pm
   
Your code is fine. What's the problem then?
gcogco10 11-Nov-20 16:30pm
   
Yes the code is fine, what i want to know. This program uses algorithm to work on recursion yes or no? If not how will improve this code?
Dave Kreskowiak 11-Nov-20 17:12pm
   
Answering the question of recursion is simple. Does the function doing the work call itself? If it does, then the answer is Yes.

You might want to look at your factorial function code to answer that.

1 solution

Quote:
This program uses algorithm to work on recursion yes or no? If not how will improve this code?

Yes. Sort of. It only ever returns 120, regardless of the value I put in num
Factorial of 3 is 120


To improve it? Don't calculate it at all. Instead, precalculate all the ones which fit in a 32 bit integer. Since there are only 13 of them (0! to 12! inclusive) it's simpler, quicker, and a lot more memory efficient to allocate an array of 13 integers, and just check that the requested value is in range. Your app either crashes or gives the wrong value if I request 13! or above ...
   
Comments
Richard MacCutchan 12-Nov-20 5:23am
   
Console.WriteLine("Factorial of " + num + " is " + factorial(5));
OriginalGriff 12-Nov-20 6:06am
   
I kinda noticed that ... but he didn't.
Nice simple little bit of debugging for him (and an indication of his testing regimen :sigh: )
Richard MacCutchan 12-Nov-20 6:18am
   
Apologies, I should have known that.
OriginalGriff 12-Nov-20 6:22am
   
No need to apologise! :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900