/* triples.c
 * written by Geoffrey Coram, gjcoram(at)yahoo(dot)com
 * free to distribute and/or modify
 * finds all Pythagorean triples (a,b,c) such that
 * a^2+b^2 = c^2, where a and b are each less than MAX
 * or the command-line argument
 */

#include <stdio.h>
#include <math.h>
#include <values.h>
#define MAX 400

int prime(int a, int b);

int main(argc, argv)
int argc;
char **argv;
{
    int a,b,c,max;
    double d;

    if (argc == 1) {
        max = MAX;
    } else if (argc == 2) {
        d = atof(argv[1]);
        if (d <= 0) {
            printf("%s should be positive.\n", argv[1]);
            exit(1);
        } else if (d >= sqrt(MAXINT)) {
            printf("%s is too large.\n", argv[1]);
            exit(1);
        } else {
            max = atoi(argv[1]);
        }
    } else {
        printf("%s: too many arguments.\n", argv[0]);
        exit(1);
    }

    for (a = 1; a <= max; a++) {
        for (b = a; b <= max; b++) {
            d = sqrt((double)(a*a + b*b));
            if (d == rint(d)) {
                if (prime(a,b))
                    printf("%d, %d, %d\n",a,b,(int)rint(d));
            }
        }
    }

    return 0;
}

int prime(int a, int b) {
    int i;
    double ai, bi;

    for (i=2; i <= a; i++) {
        ai = (double)a / i;
        bi = (double)b / i;
        if ((ai==rint(ai)) && (bi==rint(bi))) {
            return 0;
        }
    }
    return(1);
}
