In: Computer Science
(a) Provide a detailed explanation of the (signed) integer overflow. (b) Write C++ program that displays the table of function 2n . This is an integer value that you must compute using multiplication, and the use of power function pow(2.,n ) is not permitted. Display lines that contain n and 2n for n=0,1,2,3,… and show all lines that contain correct values. Stop displaying before the occurrence of the integer overflow. Your program must work on any computer and for any size of integers; so, do not try to assume some specific word size. You have to detect the overflow and prevent that it creates wrong results.
Solution:
(a)
Integer Overflow is a phenomenon where operations on 2 numbers
exceeds the maximum (or goes below the minimum) value the integer
data type can have. Usually it is thought that integral types are
very large and people don't take into account the fact that sum of
two numbers can be larger than the range. If size of a signed data
type is n bytes, it ranges from -28n-1 to
28n-1-1
So, a short(usually 2 bytes) ranges from -32768 to 32767.
(b)
#include <iostream>
using namespace std;
// Function to check integer overflow
bool isOverflow(long long a, long long b)
{
// Check if either of them is zero
if (a == 0 || b == 0)
return false;
long long result = a * b;
// Condition for multiplicative integer overflow
if (a == result / b)
return false;
else
return true;
}
//powerof function
int calcPower(long long int x, long long int y)
{
long long int result = 1;
while (y > 0)
{
if (y & 1)
{
if (isOverflow(result, x))
return -1;
result *= x;
}
y = y >> 1;
if (isOverflow(x, x))
return -1;
x = x * x;
}
return result;
}
int main()
{
long long int i, n = INT_MAX;
// loop for series, n = 0, 1, 2, .....,INT_MAX
for(i=0; i<n; i++)
{
int res = calcPower(2, i);
if(res == -1)
break;
// Print till the overflow condition gets true
cout<<2<<"^"<<i<<" = "<<res<<endl;
}
return 0;
}
OUTPUT:
If it somehow helps... plz give a like.
Good Luck :).