Project Euler #45: Triangular, pentagonal, and hexagonal
Question
Answer : 1533776805
Hacker Rank Problem
Solution
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
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, ... |
Find the next triangle number that is also pentagonal and hexagonal.
Answer : 1533776805
Hacker Rank Problem
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); long n = in.nextLong(); int a = in.nextInt(); int b = in.nextInt(); int increment = 4; for(long i=1;i<n;i++) { if(a==3) { if(isTriangularNumber(i)) System.out.println(i); if(i==1) i+=3; else if(i>4) { i+=increment+2; increment+=3; } } else { if(isHexagonalNumber(i)) System.out.println(i); if(i==1) i+=3; else if(i>4) { i+=increment+2; increment+=3; } } } } public static boolean isTriangularNumber(long n) { double tTest = Math.sqrt(1 + 8*n); return tTest == ((long)tTest); } private static boolean isHexagonalNumber(long number) { double hexTest = (Math.sqrt(1 + 8*number) + 1.0) / 4.0; return hexTest == ((long)hexTest); } } |
Comments
Post a Comment