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

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -