Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler number 45

Tags:

c

From Project Euler, problem 45:

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

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

Pentagonal 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 that is also pentagonal and hexagonal.

Here's the question. It's pretty simple and straightforward, but the thing is, my program runs into a glitch, the moment the value of the triangle number exceeds the maximum value that you can have in int data type. I've tried searching for the net for other data types but no success.

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);
     }
like image 240
Ole Gooner Avatar asked Dec 06 '11 13:12

Ole Gooner


1 Answers

Try unsigned long long. It should work.

like image 57
josh Avatar answered Oct 23 '22 12:10

josh