/*
* A186434.c
* Calculates the entries of Sloane's A186434 (counting isosceles triangles on an n X n grid)
*
* Created by Nathaniel Johnston (nathaniel@nathanieljohnston.com)
* April 23, 2011
*/

#include <math.h>
#include <stdio.h>

unsigned char pt[256][256];
FILE *file;

unsigned char isIsosceles(unsigned short a1, unsigned short a2, unsigned short b1, unsigned short b2, unsigned short c1, unsigned short c2)
{
    int sd1, sd2, sd3;
    double sqsd1, sqsd2, sqsd3;
    sd1 = (b1-a1)*(b1-a1) + (b2-a2)*(b2-a2); sqsd1 = sqrt(sd1);
    sd2 = (c1-b1)*(c1-b1) + (c2-b2)*(c2-b2); sqsd2 = sqrt(sd2);
    sd3 = (a1-c1)*(a1-c1) + (a2-c2)*(a2-c2); sqsd3 = sqrt(sd3);

    if(sqsd1 + sqsd2 > sqsd3 && sqsd2 + sqsd3 > sqsd1 && sqsd3 + sqsd1 > sqsd2 && (sd1==sd2 || sd2==sd3 || sd3==sd1))return 1;
    return 0;
}

int main ()
{
    unsigned short a, b, c, d, a1, a2, b1, b2, maxsz, sz, sz2;
    unsigned long long numPts;

    printf("This tool will calculate the entries of Sloane's A186434 (number of isosceles triangles on an n X n grid).\nPlease enter the number of terms to compute (an integer from 1 to 255): ");
    scanf("%d",&maxsz);
    numPts = 0;

    file = fopen("b186434.txt","w");
    fprintf(file,"1 0\n");
    fclose(file);
    printf("1 0\n");

    for(sz=2;sz<=maxsz;sz++){
        numPts = 0;
        sz2 = sz*sz;
        for(a=0;a<sz2;a++){
            a1 = a % sz; a2 = floor(a/sz);
            for(b=a+1;b<sz2;b++){
                b1 = b % sz; b2 = floor(b/sz);
                for(c=b+1;c<sz2;c++){
                    if(isIsosceles(a1, a2, b1, b2, c % sz, floor(c/sz))){
                        numPts++;
                    }
                }
            }
        }
        file = fopen("b186434.txt","a");
        fprintf(file,"%d %d\n",sz,numPts);
        fclose(file);
        printf("%d %d\n",sz,numPts);
    }

    printf("Done!");
    getchar();
    return 0;
}