The below program is to check whether a number (say "n") prime factors are limited to 2,3,and 5 only or not. But program gives me signed integer overflow runtime error. Can anyone please help me in solving this problem? Here's the piece of code:
bool check(int n)
{
if(n<0)
n=n*(-1); // If 'n' is negative, making it positive.
int count=1; //'count' variable to check whether the number is divisible by 2 or 3 or 5.
while(n!=1 && count)
{
count=0;
if(n%2==0)
{
n/=2; count ;
}
else if(n%3==0)
{
n/=3; count ;
}
else if(n%5==0)
{
n/=5; count ;
}
}
if(n==1)
return true;
else return false;
}
Program gave me this error:
runtime error: signed integer overflow: -2147483648 * -1 cannot be represented in type 'int'
CodePudding user response:
-2147483648 * -1 cannot be represented in type 'int' [signed 32 bit]
For sure, it cannot, and you know why? A simple fact of representation.
Imagine to have 4 bits instead of 32. You would have 1 bit for the sign and 3 for the absolute value, right?
Well, lets say you have 0 for positive numbers and 1 for negative numbers in the first bit.
Then you can only represent 2^3
=8
combinations for the absolute value, right?
Well, you only have 8 positive numbers and 8 negative numbers.
BUT 0 is considered as positive, so you have 8 negative, 7 positive and 1 neutral. So you have numbers from -8
to 7
.
In this case you have numbers from -2147483648
to 2147483647
.
CodePudding user response:
If your prime factors are limited to be 2, 3, or 5, then the easiest way is:
if (n < 0) return false;
But if your prime factors can also be -1, then just make that as an acceptable valid terminal condition.
bool check(int n) {
for (;;) {
if (n%2 == 0) {
n /= 2;
} else if (n%3 == 0) {
n /= 3;
} else if (n%5 == 0) {
n /= 5;
} else {
break;
}
}
return (n == 1) || (n == -1);
}