OK, I am actually in a bit of *rage mood* at the moment. So, I'll try to finish the question quick. I am trying to solve Problem 45 of Project Euler.
It reads:
So, after researching a bit, I summed up that every 'odd' n Triangular number is a Hexagonal number. So, if I generate Triangular numbers from after n = 285, with n being odd and check if its Pentagonal or not, I'll find the next triangle number that is also pentagonal and hexagonal. I wrote a code for that. But it doesn't give the correct result. Why? IDK. But in my program if I put n = say 283. So when n reaches 285 I get 40755 as in the question. So why doesn't it give the correct answer for the question when n > 285.Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
It can be verified that T285 = P165 = H143 = 40755.
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal Pn=n(3n-1)/2 1, 5, 12, 22, 35, ... Hexagonal Hn=n(2n-1) 1, 6, 15, 28, 45, ...
Find the next triangle number that is also pentagonal and hexagonal.
Here is my code:
Please help, I've been trying this all day.Code:#include <iostream> #include <cmath> using namespace std; bool checkPentagonal(unsigned long somenum); unsigned long genTriNum(long n); int main() { unsigned long answer = 0; for(int i = 287; answer < 1; i += 2) { unsigned long cur_tn = genTriNum(i); if(checkPentagonal(cur_tn)) { answer = cur_tn; break; } } cout << "Answer: " << answer << endl; cin.get(); cin.ignore(); return 0; } bool checkPentagonal(unsigned long somenum) { double xyz = (sqrt(double((24*somenum)+1))+1)/6; if(fmod(xyz, 2) == 0 || fmod(xyz, 3) == 0) { return true; } else { return false; } } unsigned long genTriNum(long n) { unsigned long nth_term = n*((n+1)/2); return nth_term; }