Microsoft Interview Question
Software Engineer in TestsOnce an unsigned int overflows, its value gets set to 0 so that would not work.
if (fact > 0) { return ... }
else { //overflow}
would be correct I guess for both signed and unsigned integers
1 #include <iostream>
2 #include <climits>
3
4 using namespace std;
5
6 unsigned factorial(unsigned n)
7 {
8 if(n==0||n==1)
9 return 1;
10 if(UINT_MAX/n < factorial(n-1))
11 return 0;
12 return factorial(n-1)*n;
13 }
14
15 int main()
16 {
17 cout << "factorial(4) is " << factorial(4) << endl;
18 cout << "factorial(10) is " << factorial(10) << endl;
19 cout << "UINT_MAX is " << UINT_MAX << endl;
20 cout << "factorial(20) is " << factorial(20) << endl;
21 }
Can it not be used unsigned int with some condition like
- nks December 20, 2009if ( fact < UINT_MAX ) { return ( fact( b ) ); }
else { // overflow }