Project Euler #39: Integer right triangles

Question
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?

Answer : 840

Hacker Rank Problem

Solution( But 2/7 test cases passed:(  )


 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
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++) {
            long n = in.nextLong();
            System.out.println(countSolutions(n));
        }
    }

    public static String countSolutions(long num){
        long result = 0, resultSolutions = 0;

        for (long p = 2; p <= num; p += 2) {
            int numberOfSolutions = 0;
            for (long a = 2; a < (p/3); a++) {
                if(p*(p-2*a) % (2*(p-a)) == 0){
                    numberOfSolutions++;
                }
            }

            if(numberOfSolutions > resultSolutions){
                resultSolutions = numberOfSolutions;
                result = p;
            }
        }
        return Long.toString(result);
    }
}

Comments

Popular Posts