So, recently i was doing a problem on factorials in one of the competitive coding websites where i used recursion. But on submitting it rejects my solution whereas on using a simple for loop it just accepts it. I have read many places that recursion is comparatively slower than loops, but i am still not sure if my code is rejected because of recursion or there is something really wrong. My code works fine in the IDE though.
This is my code using recursion.
UPDATE: Ok guys i asked one of my friends what could be the reason. so the reason is that the range of n was given to 1000 in the question. And if i am using recursion then factorial has to store that data which wouldnt be possible (if n==1000) because int cannot store that much(factorial of 1000) i.e why recursion wasn't accepting. I am new to S.O sorry if the question was not correctly explained I'll try asking in more detail next time so that i dont get downvotes.
int factorial(int n)
{
if(n>1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
cout<< factorial(n);
}
return 0;