Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ test for divisibility with double

why doesn´t ((num / i) % 1 == 0) work in C++ when num is a double? and how would I instead write this code, that checks for factorials by checking if it leaves a remainder (etc 0.3333).

int getFactorials (double num)
{
    int total = 0;      // if (total / 2) is equal too 'num' it is a perfect number.

    for (int i = 1; i < num; i++)
    {
        if ((num / i) % 1 == 0)
        {
            cout << i << endl;
        }
    }
    return 0;
}
like image 927
Tom Lilletveit Avatar asked Dec 07 '22 11:12

Tom Lilletveit


2 Answers

The % operator is only allowed on integral types (and user defined types which overload it). For floating point, you need the function fmod.

like image 196
James Kanze Avatar answered Dec 09 '22 15:12

James Kanze


Actually what you want to do is check if n is divisible by i so all you have to change is

if ((num / i) % 1 == 0)

into

if (num % i == 0) 

You should know that this is error-prone because you are using double as a type for num. You should use an int instead.

like image 41
alestanis Avatar answered Dec 09 '22 15:12

alestanis