Klaus Mickhelson
Klaus Mickhelson

Reputation: 43

How to check if a Number is decimal or not and apply here?

My code works perfectly fine if the total sum of given elements in vector a divided by 2 is an integer, but fails if its a double. So i need to check if the sum is double and if it is return false. I tried to do it but its not working. TestCase a= [1,2,3,5] fails here

 bool isPresent(vector<int>& a, vector<int>& v, const double& sum, int i) {
        int n = a.size();
        
        if(i == n) return false;
        if(int(sum) != (sum)) return false; // i tried like this but not working
        if(accumulate(v.begin(), v.end(), 0) == sum) return true; 
        
        if(a[i] <= sum) {
            v.push_back(a[i]);
            for(auto i=v.begin();i!=v.end();i++)
                cout << *i <<" ";
            cout << '\n';
            if(isPresent(a, v, sum, i+1)) 
                return true;
            v.pop_back();
        }
        if(isPresent(a, v, sum, i+1))
            return true;
        return false;
    }
    bool canPartition(vector<int>& a) {
        vector<int> v;
        int n = a.size();
        int s=0;
        for(int i=0;i<n;i++) {
            s += a[i];
        }
        double sum = (double)(s/2);
        if((int)sum != sum) return false; // also here
        return isPresent(a, v, sum, 0);
    }

Upvotes: 2

Views: 546

Answers (3)

chux
chux

Reputation: 154280

In addition to the bug OP has noticed, ...
... a latent bug: int(sum) is undefined when sum in not near the int range.

const double& sum
...
if(int(sum) != (sum)) return false;  // Problem code

Instead, use modf() to return the fractional part.

#include <cmath>

double whole;
double fraction = modf(sum, &whole);
if (fraction != 0.0) return false;

Upvotes: 1

scohe001
scohe001

Reputation: 15446

int sum = (double)(s/2);
if((int)sum != sum) return false; // also here

Like the other answer mentions, this is a bad cast (should be s/2.). However, you actually don't need to do this at all. A better way to check whether you can divide by two evenly would be to check the remainder of that division:

if(s % 2 != 0) { return false; }

Mod (%) divides two numbers and gives you the remainder. So if the mod (or remainder) is not 0, then we can't divide evenly.


Also note that

if(isPresent(a, v, sum, i+1))
    return true;
return false;

Can just be

return isPresent(a, v, sum, i+1);

Upvotes: 1

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

int sum = (double)(s/2);

This takes s and divides it (as an integer) by 2 (which truncates), then casts the definitely integer result to a double, then stores the result back into an int, which truncates again. Consider

double sum = ((double)s) / 2.0;

But you can avoid going through double at all by checking the modulo, which tells you the remainder under division.

if (s % 2 != 0) return false;

Upvotes: 2

Related Questions