Project Euler #75: Singular integer right triangles
Question
Answer : 161667
Hacker Rank Problem
Solution
It turns out that 12 cm is the smallest length of wire that can be
bent to form an integer sided right angle triangle in exactly one way,
but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form
an integer sided right angle triangle, and other lengths allow more
than one solution to be found; for example, using 120 cm it is possible
to form exactly three different integer sided right angle triangles.24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤
1,500,000 can exactly one integer sided right angle triangle be formed?Answer : 161667
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 | import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Solution { private static long gcd(long a, long b) { while(a != 0) { long c = a; a = b % a; b = c; } return b; } public static void main(String[] args) { int maxLength = 5 * (int) Math.pow(10, 6); int[] combinations = new int[maxLength + 1]; for(int m = 2; m < Math.sqrt(maxLength); m++) { for(int n = 1; n < m; n++) { if(((m + n) % 2) == 1) { if(gcd(m, n) == 1) { int a = m * m - n * n; int b = 2 * m * n; int c = m * m + n * n; int sum = a + b + c; int k = 1; while((k * sum) <= maxLength) { combinations[k * sum]++; k++; } } } } } ArrayList<Integer> once = new ArrayList<>(); for(int i = 0; i < combinations.length; i++) { if(combinations[i] == 1) { once.add(i); } } try(Scanner sc = new Scanner(System.in)) { int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); int pos = ~Collections.binarySearch(once, N, (x, y) -> x.compareTo(y) > 0 ? 1 : -1); System.out.println(pos); } } } } |
Comments
Post a Comment