enedil
enedil

Reputation: 1645

Why a double is negative when it ought be positive?

I want to create an application that generates full list of phone numbers that satisfies equatation:

Equatation

x is a rational number.

We can assume that

x=s/t

Now, after some transformations, we obtain

Equatation

As telephone number is integer and 10^9 is integer, we know that t * 666333999 / s is integer. Therefore s is a divisor of t * 666333999

As yet, my programm searches for all divisors of 666333999. I thing it ought do it well (it should write most of the phone numbers). Unfortunately sometimes my phone number (it's the tym variable) is a negative number.

Why is it so?

Here's my code.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector < unsigned > divisor;
    const int number = 666333999;
    long double tym;                     // it's the phone number (9 digits)
    for (int i = 2; i < number + 1; i++) 
    {                              // I'm pushing all the divisors to vector.
        if (number % i == 0)
        {
        divisor.push_back(i);
        }
    }

    for(unsigned i = 1; i < divisor.size() + 1; i++) 
    {                                      // i are consecutives values of s
        for(unsigned j = 1; j < (unsigned)2000000000; j++) 
        {                                  // j are consecutives values of t
            tym = number / divisor[i];
            tym *= j;
            if(tym > 99999999 && tym < 2000000000)  // I must substract 10^9
            {
                 cout << "\t(!)\t i = " << i << " and j = " << j << ","
                         "div[i] = " << divisor[i] << ", telephone"
                         " number = " << (tym - 1000000000) << endl;
            }
            else if(tym >= 2000000000)
            {
                break;
            }
        }
    }
}

Upvotes: 3

Views: 233

Answers (1)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20759

The number involved in your calculation exceed the capability of a 32 bit integer but may fit the 64 bit integers.

May be in your platform int is 32 bit. Just use long long.

If you want to be sure about the 64 bit, use std::int64_t, defined in <cstdint>

Upvotes: 3

Related Questions