how to self-detect when it has overflowed the value (32 bit signed integer) of a
ID: 3556345 • Letter: H
Question
how to self-detect when it has overflowed the value (32 bit signed integer) of an int variable.
It should be some conditional logic (an if statement) that breaks the loop when overflow is detected.
#include<iostream>
using namespace std;
int factorial(int n){
if (n== 1){
return 1;
}
else {
return n * factorial(n-1);
}
}
int main() {
for (int i = 0; i < 20; i++) {
cout << i+1 <<"!:" << factorial(i+1) << endl;
}
system("pause");
}
Explanation / Answer
/* factorial of number n! = 1*2*3.....*n
hence we can write n!= (n-1)!
or , n!/n = (n-1)!
Using this property
We can safely say that if this property is satisfied by the
return value of factorial function then only the
answer has not overflown.
Condition is: if(factorial(n)/n = factorial(n-1))
We need not to calculate factorial(n-1) every time as
it had been calculated in the prevoius iteration.
I am saving in a variable previousfactorial.
One observation is that factorial overflows happens after factorial(12).
if a direct rule has to be given just check : if(i<12) then only calulate factorial
otherwise print OVERFLOW.
*/
#include<iostream>
using namespace std;
int factorial(int n){
if (n== 1){
return 1;
}
else {
return n * factorial(n-1);
}
}
int main() {
int previousfactorial=1;
for (int i = 0; i < 20; i++) {
int ans = factorial(i+1);
if(((double)ans / (i+1)) == previousfactorial){
cout << i+1 <<"!:" << factorial(i+1) << endl;
previousfactorial = ans;
}
else
cout<<"OVERFLOW"<<endl;
}
system("pause");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.