Project Euler #94: Almost equilateral triangles

Question
It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).

Answer : 518408346

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

public class Solution {
    
    private static final ArrayList<Long> SO = new ArrayList<>();
    
    private static long sequence(long limit) {
        long[] plusOne = {1, 5};
        long[] minusOne = {1, 17};
        SO.clear();
        SO.add(3 * plusOne[1] + 1);
        SO.add(3 * minusOne[1] - 1);
        while(SO.get(SO.size() - 1) <= limit + 3) {
            long nextPlusOne = 14 * plusOne[1] - plusOne[0] - 4;
            long nextMinusOne = 14 * minusOne[1] - minusOne[0] + 4;
            plusOne[0] = plusOne[1];
            plusOne[1] = nextPlusOne;
            minusOne[0] = minusOne[1];
            minusOne[1] = nextMinusOne;
            SO.add(3 * nextPlusOne + 1);
            SO.add(3 * nextMinusOne - 1);
        }
        return SO.get(SO.size() - 1);
    }
    
    public static void main(String[] args) {
        SO.add(16L);
        long perimeter = 18;
        try(Scanner sc = new Scanner(System.in)) {
            int T = sc.nextInt();
            while(T-- > 0) {
                long N = sc.nextLong();
                while(perimeter <= N + 3) {
                    perimeter = sequence(N);
                }
                long sum = 0;
                sum = SO.stream().filter((x) -> (x <= N))
                                 .map((x) -> x)
                                 .reduce(sum, (accumulator, _item)
                                     -> accumulator + _item);
                System.out.println(sum);
            }
        }
    }
}

Comments

Popular Posts