otaku
otaku

Reputation: 1029

What is the error in my code?

I am solving Project Euler problem 29. I have a brute force approach just mapping all the numbers found as true if they don't exist in the map. The answer i'm getting is 9216 which is incorrect. Where is this going wrong? I've tried using a set as well but it's all the same.

int main()
{
map <long double,bool> m;
long double x;

int c=0;
for(int i=2;i<=100;i++)
{
    for(int j=2;j<=100;j++)
    {
        x=pow((long double)i,(long double)j);
        if(m.find(x) == m.end())
        {
            m.insert ( pair<long double,bool>(x,true) );
            c++;
            cout<<x<<endl;
        }
    }
}
cout<<c<<endl;

}

EDIT:
I've changed this line

m[x]=true;

to

m.insert ( pair<long double,bool>(x,true) );

The answer still the same.

Upvotes: 2

Views: 113

Answers (3)

egur
egur

Reputation: 7960

exp will produce a result in a double not long double as those are not used anymore. The compiler will convert any long double to double for you. Doubles have a limited precision and exp will return slightly different results for two operations causing the map to hold extra values.

Here's a simplified version of your code:

#include <set>

int main()
{
    set <double> m;

    for (int i = 2; i <= 100; ++i)
    {
        for (int j = 2; j <= 100; ++j)
        {
            m.insert(pow((double)i, (double)j));
        }
    }

    cout << m.size() << endl;
}

Upvotes: 0

ChronoTrigger
ChronoTrigger

Reputation: 8607

Since you are using doubles, my guess is that you obtain repeated numbers that are not exactly the same in the double representation (so they occupy different entries in the map). Try creating a map that indexes integers.

Upvotes: 4

Shrirang Kumbhar
Shrirang Kumbhar

Reputation: 363

I am not sure. but looks like you have not added entries in map "m". So, it is considering garbage values while finding.

Upvotes: 1

Related Questions