/* * 9b.c | Jim M | Sep 2010 * projecteuler.net #9, version b * * typedef, struct, malloc, and pointers. * * All this infrastructure is overkill for this simple example, * but this template works for much more complicated things. * I encourage you to study this one, and keep to a similar style. * * In fact, all the memory allocation & deallocation will * will slow this down substantially ... but this is how you * create "object like" things in C and pass around pointers to them. * */ #include #include typedef struct _triple *triple; struct _triple { int a; int b; int c; }; triple new_triple(int a, int b, int c){ // Allocate memory on the heap for this thing, and return a pointer to it. triple t = (triple) malloc(sizeof(struct _triple)); t->a = a; t->b = b; t->c = c; return t; } void free_triple(triple t){ free(t); // In a more complex struct, we'd need to free the innards. } void print_triple(triple t){ printf("a = %i, b = %i, c = %i \n", t->a, t->b, t->c); } int is_pythagorean(triple t){ // Return true if this is a pythogrean triple. return (t->a)*(t->a) + (t->b)*(t->b) == (t->c)*(t->c); } int main(){ int a, b, c; int sum = 1000; triple p; printf("Looking for triple such that a**2+b**2=c**2 and a+b+c=%i ...\n", sum); for (a = 1; a < sum-2; a++){ for (b = a+1; b < sum-2; b++){ c = sum - a - b; p = new_triple(a, b, c); if (is_pythagorean(p)){ print_triple(p); return 0; } } free_triple(p); } printf("no solution found.\n"); return 0; }