Project Euler Homework

045.cpp

00001 #include <iostream>
00002 using namespace std;
00003 
00004 bool is_tri(unsigned  x)
00005 {
00006         //solve n by iteration
00007         float n=1;
00008         float n1=1;
00009         do {
00010                 n=n1;
00011                 n1 = x/(n+1)+n/2;
00012         } while (n!=n1);
00013         return (n == (int)n); //is integer
00014 }
00015 
00016 bool is_pent(unsigned x)
00017 {
00018         //solve n by iteration
00019         double n=1;
00020         double n1=1;
00021         do {
00022                 n=n1;
00023                 n1 = n-(n*(3*n-1)-2*x)/(6*n-1);//newton's method
00024         } while (n!=n1);
00025         return (n == (int)n); //is integer
00026 }
00027 
00028 int main()
00029 {
00030         //for each hexagonal no, test if it is also a triangle no and pentagonal number
00031         for (long n=144;n>0;n++) {
00032                 unsigned  no = n*(2*n-1);
00033                 if (is_tri(no) && is_pent(no)) {
00034                         cout << no << endl;
00035                         break;
00036                 }
00037         }
00038         return 0;
00039 }
 All Classes Files Functions Variables