Friday 8 March 2013

PROJECT EULER - SOLUTION TO PROBLEM NO. 45

Here I have for all of you the solution to problem number 45, which I solved recently.
As some of my friends asked me to include comments in my code for a better understanding, I have done the same in this following program.

I am sorry for the audience that don't have the knowledge of working on the java platform as I have the following source code in java. Initially I was all prepared for working in tcpp, but tcpp being an 16-bit compiler can't satisfy my range demands, and that's why I jumped onto java platform which provides me a 32-bit environment.
Actually this is not a big issue, as I have not used any of the exclusive key features of java, and all the concepts used can be easily understood by a c or cpp programmer.

For readers' convenience I'm mentioning the 45th problem in the following lines:

Triangle, pentagonal, and hexagonal numbers are generated by the following formulas:
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, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.

/*************************************************************************/
class pr45
{
    public static void main(String args[])
    {
        long t,p,h;
        long max=100000;
        for(long i=1;i<max;i++)
        {
            t=i*(i+1)/2;//triangle number
            for(long j=1;j<max;j++)
            {
                p=j*(3*j-1)/2;//pentagonal number
                if(t==p)
                    for(long k=1;k<max;k++)
                    {   
                        h=k*(2*k-1);//hexagonal number
                        if(t==h)
                            System.out.println(t);   
                    }
            }
        }
    }
}                    

/**********************************************************************************/

Here is the output of this program....


I don't think that you will have any problem in understanding the logic of the code. Its very easy and obvious. Then also if any of the reader have any suggestion or queries then please feel free to comment...

No comments:

Post a Comment