Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
In an interview someone asked me to calculate the factorial of a number without using any loop, nd even I tried but I was not able to complete it. Kindly help me how we can calculate factorial in c# without using any loop. Just Before posting this question I tried on google , but all the answers used loop.

So Once again I posted my query on my best tutorial resource.

Kindly help me.

Thanks.
Posted
Comments
ridoy 4-Jun-14 4:17am    
If you will think it straightforward, then you can definitely answer it. Without loop it can be done in a smarter way, and guess what? That is called recursion!

I am not sure this is the correct answer it should be possible using recursive fuction.


C#
int fact(int n)
{
    if(n==0)
       return 1;
    else
       return n * fact(n-1);
}
 
Share this answer
 
v2
Comments
Naz_Firdouse 4-Jun-14 1:33am    
As per my knowledge, having if(n<=1) return 1; is the best approach.
Because it lessens one recursive call which gives the same result.

If we follow the above approach,
If n=1;
we call 1* fact(0)
where fact(0) returns 1 and then the end result is 1.

Instead if we use if(n <=1) return 1; condition....
it directly returns 1 in a single call.

I hope I am clear.
[no name] 4-Jun-14 1:47am    
Good but wrong answer if -ve n.
Naz_Firdouse 4-Jun-14 3:10am    
Thanks...but how the code mentioned in the solution works for negative numbers???
[no name] 4-Jun-14 1:44am    
Unfortunately it won't like -ve n.
Naz_Firdouse 4-Jun-14 3:18am    
The code mentioned in the solution throws "StackOverflowException" is negative values are passed to the function...
Hi,

C#
public int fact(int n)
{
    if (n==0) return 1;
    else return n*fact(n-1)
}


Thanks,
Bh@gyesh
 
Share this answer
 
Comments
Naz_Firdouse 4-Jun-14 1:33am    
As per my knowledge, having if(n<=1) return 1; is the best approach.
Because it lessens one recursive call which gives the same result.

If we follow the above approach,
If n=1;
we call 1* fact(0)
where fact(0) returns 1 and then the end result is 1.

Instead if we use if(n <=1) return 1; condition....
it directly returns 1 in a single call.

I hope I am clear.
you can use recursive method which calls itself so many times until being satisfied.
check below links for more information
Recursive methods using C#[^]
C# - Factorial With and With out using Recursive Functions[^]
 
Share this answer
 
C#
int Factorial(int n)
{
     if (n <= 1)
          return 1;
     return n * Factorial(n - 1);
}
 
Share this answer
 
Comments
[no name] 4-Jun-14 3:55am    
Returns 1 for factorial of negative number. Not good.

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