Euler Project No. 45

From Project Euler, issue 45 :

Triangular, pentagonal and hexagonal numbers are generated using the following formulas:

Triangle T_ (n) = n (n + 1) / 2 1, 3, 6, 10, 15, ...

The pentagon P_ (n) = n (3n-1) / 2 1, 5, 12, 22, 35, ...

Hexagonal H_ (n) = n (2n-1) 1, 6, 15, 28, 45, ...

It can be verified that T_ (285) = P_ (165) = H_ (143) = 40755.

Find the next triangle number, which is also pentagonal and hexagonal.

That is the question. It is quite simple and simple, but the fact is that my program starts with an error when the value of the number of triangles exceeds the maximum value that you can have in the int data type. I tried to find a network for other data types, but did not succeed.

the code

     #include<stdio.h>
     int main(void)
     {
        int i,j,t,h,p,k;
        int n=10000;
        for(i=0;i<n;i++)
        {
            t=(i*(i+1))/2;
            for(j=0;j<n;j++)
            {   
                h=j*(2*j-1);
                if(h>t)
                break;
                if(h==t)
                {   
                    //printf("%d %d\n",h,t);
                    for(k=0;k<n;k++)
                    {
                        p=(k*(3*k-1))/2;
                        if(p>h)
                        break;
                        if(p==h)
                        {
                            printf("%d %d\n",p,i);
                            break;
                        }   
                    }   
                }

            }   
        }       
        printf("done\n");
        return(0);
     }
+5
source share
1 answer

Try unsigned long long. It should work.

+5
source

All Articles