Project Euler > Problem 45 > Triangular, pentagonal, and hexagonal (Java Solution)

Problem:

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

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.


Solution:

1533776805


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 45
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p045 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p045().run());
 }
 
 
 public String run() {
  int i = 286;
  int j = 166;
  int k = 144;
  while (true) {
   long triangle = (long)i * (i + 1) / 2;
   long pentagon = (long)j * (j * 3 - 1) / 2;
   long hexagon  = (long)k * (k * 2 - 1);
   long min = Math.min(Math.min(triangle, pentagon), hexagon);
   if (min == triangle && min == pentagon && min == hexagon)
    return Long.toString(min);
   if (min == triangle) i++;
   if (min == pentagon) j++;
   if (min == hexagon ) k++;
  }
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact