c++ - Code for Project Euler No 45 not working -


here problem, project euler #45

and here's code wrote it:

#include <iostream> #include <math.h> using namespace std;  bool ispent (long num){     long double x = (sqrt(24*num+1) + 1.0)/6.0;     if (floor(x)==x) return true;     else return false; }  bool ishex (long num){     long double x = (sqrt(8*num+1) + 1.0)/4.0;     if (floor(x)==x) return true;     else return false; }  int main(){     int i=286;     while(true){         long x = (i*(i+1))/2;         if((ispent(x)) && (ishex(x))){             cout << x;             break;         }         i++;     } } 

this gives output 40755, whereas require next number. possible bug?

the issue using square roots check if number pentagonal or hexagonal imprecise, test fail , overflow x.

to fix this, can use type more precision, replacing long unsigned long, or unsigned long long.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -