-1

I have this code that works for most of the inputs but there are some that throw me error. like " -1000000000000000000 1 1000000000000000000 " for example.

#include <iostream>
#include <cstdio>

using namespace std;
int x,y,m;
int aux=0;
int toPerfect(int a,int b,int per){
    if(a >= per || b >= per){
         aux=0;

    }else if(a<=0 && b<=0){
                 aux = -1;
           }else{
                 while(a < per && b < per){
                      if(a > b){
                           b = b+a;
                       }else{
                             a = a+b;   
                            }
                      aux++;        
                }
               }

     return aux;
}

int main(){
    cin >>x>>y>>m;
    cout << toPerfect(x,y,m) << endl;
    cin.get();

}
LET1S3N
  • 28
  • 7

2 Answers2

2

You're looking at an Integer Overflow. This question is asked so often here there should perhaps be a dedicated forum with this name.

...an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is too large to be represented within the available storage space. For instance, adding 1 to the largest value that can be represented constitutes an integer overflow. The most common result in these cases is for the least significant representable bits of the result to be stored (the result is said to wrap).

Ken
  • 30,811
  • 34
  • 116
  • 155
2

The range of some datatypes I've mentioned here. Check it out change your code according to requirements.

signed char: -127 to 127
unsigned char: 0 to 255
signed short: -32767 to 32767
unsigned short: 0 to 65535
signed int: -32767 to 32767
unsigned int: 0 to 65535
signed long: -2147483647 to 2147483647
unsigned long: 0 to 4294967295
signed long long: -9223372036854775807 to 9223372036854775807
unsigned long long: 0 to 18446744073709551615
netX
  • 134
  • 4
  • 12