Problem was to find the factorial of the small integer taking test cases T
</>
include
using namespace std;
int fact(int n){
if(n>1)
{
int smalloutput =fact(n-1);
int output = n* smalloutput;
return output;
}
if(n<0)
{
int smalloutput =fact(-n-1);
int output = -n* smalloutput;
return -output;
}
else
{return 1;}
}
int main() {
int t;
cin>>t;
int a[t];
for (int i=0; i<t;i++)
{
cin>>a[i];
}
for (int i=0; i<t;i++){
int x = a[i];
cout<<fact(x)<<endl;
}
return 0;
}
I think error lies in how negative numbers are handled within the fact function. Within the fact function, negative numbers are handled by adjusting their sign to positive and then calculating the factorial of the positive equivalent. This adjustment ensures that the factorial is calculated correctly for negative numbers. So,the corected code will be
int fact(int n) {
if (n > 1) {
return n * fact(n - 1);
} else if (n < 0) {
return -fact(-n);
} else {
return 1;
}
}
int main() {
int t;
cin >> t;
int a[t];
for (int i = 0; i < t; i++) {
cin >> a[i];
}
for (int i = 0; i < t; i++) {
int x = a[i];
cout << fact(x) << endl;
}
return 0;
}
here, negative numbers are handled by adjusting their sign and then taking the factorial of the positive equivalent. This eliminates the need for separate handling of negative numbers and ensures the correct factorial calculation.
Thank You!