Integer Triangles in Java


The challenge

You have to give the number of different integer triangles with one angle of 120 degrees which perimeters are under or equal a certain value. Each side of an integer triangle is an integer value.

// number of integer triangles,
give_triang(max. perimeter)

with sides a, b, and c integers such that:

a + b + c <= max. perimeter

See some of the following cases

// No Integer triangles with perimeter under or equal five
give_triang(5) // 0

// One integer triangle of (120 degrees). It's (3, 5, 7)
give_triang(15) // 1

// Three triangles: (3, 5, 7), (6, 10, 14) and (7, 8, 13)
give_triang(30) // 3

// (3, 5, 7), (5, 16, 19), (6, 10, 14), (7, 8, 13) and (9, 15, 21) are the triangles with perim under or equal 50.
give_triang(50) // 5

The solution in Java code

Option 1:

public class IntTriangles {
    public static int giveTriang(int per) {
        int cnt = 0; int a = 3;
        while (a < per) {
            if (2*a > per) break;
            int b = a;
            while (b < per) {
                if (a + 2*b > per) break;
                double c = Math.sqrt(a*a + a*b + b*b);
                if ((c % 1 == 0) && (a+b+c <= per))
                    cnt++;
                b++;
            }
            a++;
        }
        return cnt;
    }
}

Option 2:

public class IntTriangles {
    public static int giveTriang(int per) {
        int res = 0;
        for(int i =1;i<per-1;i++)
          for(int j = i;j<per-1;j++){
            double k = Math.sqrt(i*i+i*j+j*j);
            if(i+j+k<=per&&i+j>k&&j+k>i&&k+i>j&&k%1==0)
              res++;
            }
        return res;
    }
}

Option 3:

public class IntTriangles {
    public static int giveTriang(int per) {
        int count = 0;
        for (int a = 1; a < per / 2; a++) {
            for (int b = 1; b < a; b++) {
                double cSquare = a * a + b * b + a * b;
                int c = (int)Math.sqrt(cSquare);
                if (c * c == cSquare && a + b + c <= per) {
                    count++;
                }
            }
        }
        return count;
    }
}

Test cases to validate our solution

import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;

public class IntTrianglesTest {

    private static void testing(int i, int results) {
        assertEquals(results, i);
    }
    public static void tests(int[] list1, int[] results) {
        for (int i = 0; i < list1.length; i++)
            testing(IntTriangles.giveTriang(list1[i]), results[i]);
        return;
    }  
    @Test
    public void test1() {
        System.out.println("Basic Tests");
        int[] list1 = new int[] {5, 15, 30, 50, 80, 90, 100, 150, 180, 190};
        int[] results = new int[] {0, 1, 3, 5, 11, 13, 14, 25, 32, 35};
        tests(list1, results);
    }
}